在foreach中使用LINQ语句是否在每次迭代时重新评估语句

时间:2015-07-16 15:05:10

标签: c# linq foreach

所以我想知道在我的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
}

或者他们都以完全相同的方式工作?

3 个答案:

答案 0 :(得分:2)

foreach (var thing in myExpression)调用myExpression.GetEnumeratorMoveNext,直到它返回false。所以你的两个片段是一样的。

(顺便提一下,GetEnumeratorIEnumerable上的方法,但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循环

中迭代