是否可以通过布尔条件将IEnumerable分为两个,而无需两个查询? [英] Can I split an IEnumerable into two by a boolean criteria without two queries?
本文介绍了是否可以通过布尔条件将IEnumerable分为两个,而无需两个查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用LINQ和仅一个查询/LINQ语句将IEnumerable<T>
分为两个IEnumerable<T>
吗?
Can I split an IEnumerable<T>
into two IEnumerable<T>
using LINQ and only a single query/LINQ statement?
我想避免两次遍历IEnumerable<T>
.例如,是否可以合并下面的最后两个语句,使allValues仅被遍历一次?
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();
推荐答案
您可以使用此
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];
这篇关于是否可以通过布尔条件将IEnumerable分为两个,而无需两个查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文