Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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(); 
like image 366
SFun28 Avatar asked Dec 28 '10 20:12

SFun28


1 Answers

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]; 
like image 176
Mark Byers Avatar answered Oct 06 '22 06:10

Mark Byers