这是示例数据库表
Name | Quantanity
Book I | 1
Book II | 13
Book III | 5
etc...
我想选择这些行,直到我有100本书使用LINQ表达式。
我在尝试
.TakeWhile(x => (amount -= x.Quantanity) > 0);
但它给了我一个错误
“表达式树不能包含赋值运算符”
答案 0 :(得分:5)
int bookCount = 0;
var query = books
.OrderBy(b => b.Quantity) // to get count 100, otherwise exceed is likely
.AsEnumerable()
.Select(b => {
bookCount += b.Quantanity;
return new { Book = b, RunningCount = bookCount };
})
.TakeWhile(x => x.RunningCount <= 100)
.Select(x => x.Book);
答案 1 :(得分:1)
AsEnumerable()
之前的部分 - 基本上,您将整个表拉入内存,然后处理它。
让我们看看我们是否可以改善这一点:
int bookCount = 0;
var query1 = (from b in books
where b.Quantity > 0 && b. Quantity <= 100
orderby b.Quantity
select b).Take(100).AsEnumerable();
var query = query1
.Select(b => {
bookCount += b.Quantity;
return new { Book = b, RunningCount = bookCount };
})
.TakeWhile(x => x.RunningCount <= 100)
.Select(x => x.Book);
这限制了我们在内存中只有100条记录才能通过计数达到100。