This is example database table
Book I | 1 Book II | 13 Book III | 5 etc...
And I want to select this rows until I will have 100 books usinq LINQ expression.
I was trying
.TakeWhile(x => (amount -= x.Quantanity) > 0);
But it gave me an error
"Expression tree cannot contain assignment operator"
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);
Tim's solution is good, but note about it --- Only the part before the AsEnumerable()
is being executed by the data server -- Basically, you are pulling the entire table into memory, and then processes it.
Let's see if we can improve that:
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);
This limits us to only 100 records in memory to look thru to get to a count of 100.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.