Section data based on a condition ("where") in a single query?

I have some data that I need to break down based on some condition, i.e.:

var trues = from item in items where MyCondition(item, blah) select item; var falses = from item in items where !MyCondition(item, blah) select item; 

Is there a cleaner way to do this in a single query and return both results so that I don't have to repeat myself (and finish iterating over the data twice) as above?

+4
source share
1 answer

If you do not want to iterate over the data twice, you will have to create a LINQ query containing true values ​​and false values ​​with the indicator to which they belong.

You can do this using ToLookup :

 var combined = items.ToLookup(x => MyCondition(x, blah)); var trues = combined[true]; var falses = combined[false]; 
+4
source

Source: https://habr.com/ru/post/1487835/


All Articles