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

前端 未结 3 830
再見小時候
再見小時候 2020-12-01 02:19

Can I split an IEnumerable into two IEnumerable using LINQ and only a single query/LINQ statement?

I want to avoid iter

3条回答
  •  青春惊慌失措
    2020-12-01 03:05

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

    IEnumerable allValues = ...
    ILookup theLookup = allValues.ToLookup(val => val.SomeProp);
    
      //does not throw when there are not any true elements.
    List trues = theLookup[true].ToList();
      //does not throw when there are not any false elements.
    List 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 trues = theLookup[true];
    IEnumerable falses = theLookup[false];
    

提交回复
热议问题