所以我想知道在我的LINQ where
循环中使用foreach
子句是否意味着在每次迭代时它将重新评估我的LINQ where
子句。例如:
var MyId = 1;
foreach (var thing in ListOfThings.Where(x => x.ID == MyId))
{
//do Something
}
或者写作更好:
var MyId = 1;
var myList = ListOfThings.Where(x => x.ID == MyId);
foreach (var thing in myList)
{
//do Something
}
或者他们都以完全相同的方式工作?
答案 0 :(得分:2)
foreach (var thing in myExpression)
调用myExpression.GetEnumerator
和MoveNext
,直到它返回false。所以你的两个片段是一样的。
(顺便提一下,GetEnumerator
是IEnumerable
上的方法,但myExpression
不一定是IEnumerable
;只是GetEnumerator
的内容法)。
答案 1 :(得分:1)
此示例应该为您提供所需的所有答案:
using System;
using System.Linq;
public class Test
{
public static void Main()
{
// Create sequence of integers from 0 to 10
var sequence = Enumerable.Range(0, 10).Where(p =>
{
// In each 'where' clause, print the current item.
// This shows us when the clause is executed
Console.WriteLine(p);
// Make sure every value is selected
return true;
});
foreach(var item in sequence)
{
// Print a marker to show us when the loop body is executing.
// This helps us see if the 'where' clauses are evaluated
// before the loop starts or during the loop
Console.WriteLine("Loop body exectuting.");
}
}
}
0
Loop body exectuting.
1
Loop body exectuting.
2
Loop body exectuting.
3
Loop body exectuting.
4
Loop body exectuting.
5
Loop body exectuting.
6
Loop body exectuting.
7
Loop body exectuting.
8
Loop body exectuting.
9
Loop body exectuting.
在每次循环迭代开始时,对于当前元素,Where
子句被计算一次。
答案 2 :(得分:0)
从评论中我得出结论foreach
循环在每次迭代时都没有重新评估我的LINQ where
。
从MSDN Enumerable.Where我可以看到此方法返回IEnumerable
返回值类型:System.Collections.Generic.IEnumerable An IEnumerable包含来自输入序列的元素 满足条件。
然后在foreach
循环