Home > database >  C# Linq Nested GroupBy
C# Linq Nested GroupBy

Time:02-01

I have the following list:

List<int> x = new List<int>() { 
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10 
};

I'd like to break it down to groups twice:

  1. First grouping into odd & even numbers (I managed to do that)
  2. For each group: group each number to a group of numbers >= 5.

The expected output should be:

[[1,3],[5,7,9]] , [[2,4], [6,8,10]]

I managed to break it down to the first group by using:

var y = x
  .GroupBy(x => x % 2)
  .Select(g => g.ToList())
  .ToList();

But I don't know where to go from there..

CodePudding user response:

Just keep on GroupBy groups:

// y is List<List<List<int>>>
var y = x
  .GroupBy(item => item % 2)         // first odds and evens
  .Select(group => group             // then each group
    .GroupBy(item => item >= 5)      // into big (>= 5) and small
    .Select(inner => inner.ToList()) // we want list 
    .ToList())                       // .. of list ..
  .ToList();                         // .. of list materialization

Please, fiddle, yourself

  • Related