Using LINQ to group numbers

c#, functional-programming, linq

Solution

Easy.

var results = xs.Aggregate<int, List<List<int>>>(
    new List<List<int>> { new List<int>() },
    (a, n) =>
    {
        if (a.Last().Sum() + n > 5)
        {
            a.Add(new List<int> { n });
        }
        else
        {
            a.Last().Add(n);
        }
        return a;
    });

So, from this:

var xs = new [] { 3, 3, 1, 2, 3, 2, };

I get this:

Problem

Suppose if I have a list of numbers like this, ``` [3, 3, 1, 2, 3, 2] ``` and I'd like to group them together in a sequence such that the sum of each group is less or equal to five, i.e. the correct answer is: ``` [3], [3, 1], [2,3], [2] ``` Is there a way to express this using Linq?

Original source