This is example database table
Name | Quantanity
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With