Accepted answer
  • Instead of putting it into an own list by calling ToList() or ToArray() i would prefer to use AsEnumerable().
  • Additionally like the others you should try OrderByDescending()
  • Instead of Count() i would use Any().


Yet another way get last element without orderbydescending and load all entities:

var lastBill = purchaseBills
    .Where(f => f.BillID == purchaseBills.Max(f2 => f2.BillID))


You can convert your IEnumerable into a List using the ToList() method, which will ensure that all your attempts are successful, as shown:

var purchaseBills = db.PurchaseBills.OrderBy(p => p.BillID);

if (purchaseBills.Any())
  var firstBill = purchaseBills.First(); // This is supported

// Attempt 1                    
  var lastBill = purchaseBills.ToList().Last();

// Attempt 2
  var lastBill = purchaseBills.ToList().LastOrDefault(); 

  var lastBill = purchaseBills.ToList().Reverse().First();

  textBoxPurchaseBillFrom.Text = firstBill.BillNo.ToString();
  textBoxPurchaseBillTo.Text = lastBill.BillNo.ToString();


It has something to do with the fact that the Last operator is trying to be sent to the SQL server which has no corresponding command. Once solution is to put a ToArray() or Tolist() at the end of your db call which makes that one line an explicit call to get the data (instead of lazing loading on each of the other lines).


I try not to use LastOrDefault() because sometime it doesn't work or support. I'm sorting id by desc and then grab the first records.

.FirstOrDefault(s => s.Name == Name)


The problem is that there's no easy translation into SQL for Last or Reverse, so either convert it to something in memory (ToList, ToArray) if there aren't going to be too many records, or you could run the query a 2nd time, with OrderByDescending instead of OrderBy and use First.


Last is not supported by the back-end DB. You should try other techniques:

  1. Run your query using OrderByDescending so your requested item comes first.

  2. Code your LINQ query as usual, but enforce Linq2Sql to render it to a CLR collection and then you'll have free access to everything locally, including Last. Example:

    var bills = purchaseBills.ToList();
    var last = bills.Last();


either you switch your OrderBy to

.OrderByDescending(p => p.BillID)

(and use first) or you do something like


if this is not to expensive.

Related Query

More Query from same tag