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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With