I have the following list. I’m trying to split it into odd & even lists using GroupBy
:
var x = new int[] { 2, 4, 6, 8, 10 };
var y = x
.GroupBy(x => x % 2 == 0)
.Select(x => x.ToList())
.ToList();
This outputs a List<List<int>>
, the problem is that it doesn’t insert null groups into the list, so the list has only 1 item in it.
I’d like for the absent values to be inserted as an empty list, so that when I do:
var odds = y[1] // => empty list instead of out of range
I tried doing the following:
var y = x
.GroupBy(x => x % 2 == 0)
.Select(x => x.ToList() ?? new List<int>())
.ToList();
>Solution :
I suggest using GroupJoin
; we form all required groups’ keys with Enumerable.Range(0, 2)
and then join x
to them:
var x = new int[] { 2, 4, 6, 8, 10 };
var y = Enumerable
.Range(0, 2)
.GroupJoin(x,
a => a,
b => b % 2,
(key, items) => (key : key, list : items.ToList()))
.ToList();