Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在foreach中使用LINQ语句是否会在每次迭代中重新计算该语句_C#_Linq_Foreach - Fatal编程技术网

C# 在foreach中使用LINQ语句是否会在每次迭代中重新计算该语句

C# 在foreach中使用LINQ语句是否会在每次迭代中重新计算该语句,c#,linq,foreach,C#,Linq,Foreach,所以我想知道的是,在我的foreach循环中使用linqwhere子句是否意味着在每次迭代中它都会重新计算我的linqwhere子句。例如: 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
循环中使用
linqwhere
子句是否意味着在每次迭代中它都会重新计算我的
linqwhere
子句。例如:

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
}

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

因此,从我的评论中可以看出,
foreach
循环不会在每次迭代中重新评估我的
LINQ where

从中可以看出,此方法返回一个
IEnumerable

返回值类型:System.Collections.Generic.IEnumerable An IEnumerable,包含输入序列中的元素 满足条件

然后在
foreach
循环中对其进行迭代

foreach(myExpression中的var thing)
调用
myExpression.GetEnumerator
MoveNext
直到返回false。所以你的两个片段是一样的


(顺便说一句,
GetEnumerator
IEnumerable
上的一个方法,但是
myExpression
不一定是
IEnumerable
;只需使用
GetEnumerator
方法即可)。

此示例应为您提供所需的所有答案:

代码 输出 结论
Where
子句在每次循环迭代开始时对当前元素求值一次。

最后一个问题:是的,这是相同的:-)任何方式
Where
都返回迭代器,因此只需执行一次IL反汇编程序并反汇编两个代码,然后你会看到是否有difference@IssaJaber两者的IL永远不可能是相同的。。他的问题是它们是否具有相同的功能。。。这是一个好主意,不过我必须补充一点,
TestFunc
将对列表中的每个项目执行,因此真正的测试是
TestFunc
执行的次数与
list.Count
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.