I want to group objects by a boolean
value, and I need to always get two groups (one for true
, one for false
), no matter if there are any elements in them.
The usual approach using GroupBy
does not work, as it will only generate nonempty groups. Take e.g. this code:
var list = new List<(string, bool)>();
list.Add(("hello", true));
list.Add(("world", false));
var grouping = list.GroupBy(i => i.Item2);
var allTrue = grouping.Last();
var allFalse = grouping.First();
This only works if there is at least one element per boolean
value. If we remove one of the Add
lines, or even both, allTrue
and allFalse
will not contain the correct groups. If we remove both, we even get a runtime exception trying to call Last()
("sequence contains no elements").
Note: I want to do this lazily. (Not: Create two empty collections, iterate over the input, fill the collections.)