score:54

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().

score:1

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

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

score:1

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(); 

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

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

score:4

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).

score:10

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.

.OrderByDescending(o=>o.id)
.FirstOrDefault(s => s.Name == Name)

score:11

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.

score:20

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();
    

score:28

either you switch your OrderBy to

.OrderByDescending(p => p.BillID)

(and use first) or you do something like

purchaseBills.ToArray().Last()

if this is not to expensive.


Related Query

More Query from same tag