Nick Nick - 1 year ago 59
C# Question

Using Linq to sum up to a number (and skip the rest)

If we have a class that contains a number like this:

class Person
public string Name {get; set;}
public int Amount {get; set;}

and then a collection of people:

IList<Person> people;

That contains, let's say 10 people of random names and amounts
is there a Linq expression that will return me a subcollection of Person objects whose sum fulfills a condition?

For example I want the first x people whose sum of Amount is under 1000.
I can do that traditionally by

var subgroup = new List<Person>();

people.OrderByDescending(x => x.Amount);

var count = 0;
foreach (var person in people)
count += person.Amount;
if (count < requestedAmount)

But i've been wondering if there's an elegant Linq way of doing something like this using Sum and then some other function like Take?


This is fantastic:

var count = 0;
var subgroup = people
.OrderByDescending(x => x.Amount)
.TakeWhile(x => (count += x.Amount) < requestedAmount)

But I am wondering if I can somehow change it further in order to grab the next person in the people list and add the remainder into the sum so that the total amount equals requested amount.

Answer Source

You can use TakeWhile:

int s = 0;
var subgroup  = people.OrderBy(x => x.Amount)
                      .TakeWhile(x => (s += x.Amount) < 1000)

Note: You mention in your post first x people. One could interpret this as the ones having the smallest amount that adds up until 1000 is reached. So, I used OrderBy. But you can substitute this with OrderByDescending if you want to start fetching from the person having the highest amount.


To make it select one more item from the list you can use:

.TakeWhile(x => {
                   bool bExceeds = s > 1000;
                   s += x.Amount;                                 
                   return !bExceeds;

The TakeWhile here examines the s value from the previous iteration, so it will take one more, just to be sure 1000 has been exceeded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download