问题描述
我正在尝试获取列表中的第一个和最后一个值.支持查询运算符 First(),但 Last() 和 LastOrDefault() 会出错.我是否错误地使用了 Last() 运算符?
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 error. Am I using the Last() operator incorrectly?
var purchaseBills = db.PurchaseBills.OrderBy(p => p.BillID);
if (purchaseBills.Count() >0)
{
var firstBill = purchaseBills.First(); // This is supported
// Attempt 1
var lastBill = purchaseBills.Last(); // Not supported
// Attempt 2
var lastBill = purchaseBills.LastOrDefault(); // Not supported
//Attempt 3
var lastBill = purchaseBills.Reverse().First(); // Not supported
textBoxPurchaseBillFrom.Text = firstBill.BillNo.ToString();
textBoxPurchaseBillTo.Text = lastBill.BillNo.ToString();
}
更新:
--错误--
尝试 1:不支持查询运算符Last".
Attempt 1: The query operator 'Last' is not supported.
尝试 2:不支持查询运算符LastOrDefault".
Attempt 2: The query operator 'LastOrDefault' is not supported.
尝试 3:不支持查询运算符Reverse".
Attempt 3: The query operator 'Reverse' is not supported.
推荐答案
- 我宁愿使用 AsEnumerable(),而不是通过调用 ToList() 或 ToArray() 将其放入自己的列表中.
- 另外像其他人一样,您应该尝试 OrderByDescending()
- 我会使用 Any() 而不是 Count().
- 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().
买了我的瓜就忘了那个他