I am trying to get the first and last values in a list. The query operator First()
is supported but Last()
and LastOrDefault()
give an
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.
ToList()
or ToArray()
i would prefer to use AsEnumerable()
.OrderByDescending()
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))
.FirstOrDefault();
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)
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).
Last
is not supported by the back-end DB. You should try other techniques:
Run your query using OrderByDescending
so your requested item comes first.
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();