我有一个项目列表,我想遍历其中的一个子集。现在,我想知道从列表中删除不需要的项目然后循环遍历它之间是否存在性能影响差异;或者简单地在 for 循环中过滤列表。
这是一个例子。
RemoveAll 方法:
list.RemoveAll(o => !someOtherList.Contains(o.Property));
foreach (var i in list)
{
}
Where 方法:
foreach (var i in list.Where(o => someOtherList.Contains(o.Property))
{
}
我知道第一种方法实际上是要操纵列表中的内容,而第二种方法不会。这与我无关。我更关心的是第二种方法中的过滤器是否应用于每次迭代,或者 C# 是否足够智能以创建一个子集并仅循环遍历该子集(几乎就像第一种使用临时变量的方法)。
最佳答案
I am more concerned as to whether the filter in the second approach is applied for each iteration or whether C# is smart enough to create a subset and only loop through that subset (almost like the first approach with a temp variable)
Linq 的 Where
使用 yield以便在请求后一次返回一个元素。
所以实际上在第二种方法中所做的是:
1- 遍历列表
2-检查当前元素是否匹配条件(循环通过someOtherList除非它是一个特殊的查找数据结构,例如。HashSet
)
3- 一旦我们找到第一个元素就返回它
4-执行foreach主体逻辑
5- 从我们在第 3 步停止的地方继续搜索
这意味着如果您决定根据 foreach block 内的某些条件进行中断,那么可能不会在该点扫描所有列表,这在某些情况下可能会提高大型列表的性能。
关于c# - .RemoveAll 和 .Where 在 C# 中的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40626696/