Can I split an IEnumerable into two by a boolean criteria without two queries?

Some people like Dictionaries, but I prefer Lookups due to the behavior when a key is missing.

IEnumerable<MyObj> allValues = ...
ILookup<bool, MyObj> theLookup = allValues.ToLookup(val => val.SomeProp);

// does not throw when there are not any true elements.
List<MyObj> trues = theLookup[true].ToList();
// does not throw when there are not any false elements.
List<MyObj> falses = theLookup[false].ToList();

Unfortunately, this approach enumerates twice – once to create the lookup, then once to create the lists.

If you don’t really need lists, you can get this down to a single iteration:

IEnumerable<MyObj> trues = theLookup[true];
IEnumerable<MyObj> falses = theLookup[false];

Leave a Comment