Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group items by total amount

Suppose I have this number list:

List<int> nu = new List<int>();
nu.Add(2);
nu.Add(1);
nu.Add(3);
nu.Add(5);
nu.Add(2);
nu.Add(1);
nu.Add(1);
nu.Add(3);

Keeping the list items in the same order, is it possible to group the items in linq that are sum of 6 so results would be something like this:

2,1,3 - 5 - 2,1,1 - 3
like image 737
Chris Avatar asked Aug 01 '12 13:08

Chris


1 Answers

Solving this with LINQ directly would be bothersome, instead you could make an extension method:

// Assumptions:
//  (1) All non-negative, or at least you don't mind them in your sum
//  (2) Items greater than the sum are returned by their lonesome
static IEnumerable<IEnumerable<int>> GroupBySum(this IEnumerable<int> source,
    int sum)
{
    var running = 0;
    var items = new List<int>();
    foreach (var x in source)
    {
        if (running + x > sum && items.Any())
        {
            yield return items;
            items = new List<int>();
            running = 0;
        }

        running += x;
        items.Add(x);
    }

    if (items.Any()) yield return items;
}
like image 72
user7116 Avatar answered Oct 02 '22 14:10

user7116