Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ select until amount >= 0

Tags:

c#

linq

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"

like image 923
Kermax Avatar asked Nov 01 '25 00:11

Kermax


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);
like image 179
Tim Schmelter Avatar answered Nov 03 '25 13:11

Tim Schmelter


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.

like image 44
James Curran Avatar answered Nov 03 '25 13:11

James Curran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!