C # LINQ select up to sum> = 0
This is a sample database table
Name | Quantanity
Book I | 1
Book II | 13
Book III | 5
etc...
And I want to select these lines until I have 100 words of usinq LINQ.
I have tried
.TakeWhile(x => (amount -= x.Quantanity) > 0);
But it gave me an error
"Expression tree cannot contain an assignment operator"
+3
source to share
2 answers
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);
+5
source to share
Solution by type is good, but pay attention to it --- Only the part before AsEnumerable()
is executed by the data server. Basically, you pull the entire table into memory and then process it.
Let's see if we can improve this:
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 entries in memory to view up to 100.
+1
source to share