Last and LastOrDefault not supported

后端 未结 7 1047
孤独总比滥情好
孤独总比滥情好 2020-12-03 09:47

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

相关标签:
7条回答
  • 2020-12-03 09:59

    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.

    0 讨论(0)
  • 2020-12-03 10:01
    • 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().
    0 讨论(0)
  • 2020-12-03 10:07

    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();
    
    0 讨论(0)
  • 2020-12-03 10:09

    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)
    
    0 讨论(0)
  • 2020-12-03 10:09

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

    0 讨论(0)
  • 2020-12-03 10:16

    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();
      
    0 讨论(0)
提交回复
热议问题