【发布时间】:2012-11-22 14:52:49
【问题描述】:
如果我有收藏:
List<T> collection;
而且我需要对这个集合进行两次测试,这样效率更高:
foreach(T t in collection.where(w => w.value == true))
{
t.something = true;
}
foreach(T t in collection.where(w => w.value2 == true))
{
t.something2 = true;
}
或者
foreach(T t in collection)
{
if (t.value == true)
{
//check 1
}
if (t.value2 == true)
{
//check 2
}
}
我认为会是后者,因为我假设每个 where 都会迭代集合,但只是想确保我没有遗漏什么?
【问题讨论】:
-
严格来说,迭代的是
foreach。Where只是设置了一个过滤(但非迭代)的包装器。 -
你也可以使用
Any-extension:t.something = collection.Any(w => w.value);,虽然它只测试其中一个集合...