Can I split an IEnumerable<T>
into two IEnumerable<T>
using LINQ and only a single query/LINQ statement?
I want to avoid iterating through the IEnumerable<T>
twice. For example, is it possible to combine the last two statements below so allValues is only traversed once?
IEnumerable<MyObj> allValues = ... List<MyObj> trues = allValues.Where( val => val.SomeProp ).ToList(); List<MyObj> falses = allValues.Where( val => !val.SomeProp ).ToList();
You can use this:
var groups = allValues.GroupBy(val => val.SomeProp);
To force immediate evaluation like in your example:
var groups = allValues.GroupBy(val => val.SomeProp) .ToDictionary(g => g.Key, g => g.ToList()); List<MyObj> trues = groups[true]; List<MyObj> falses = groups[false];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With