How does the following LINQ statement work?

Here is my code:

var list = new List<int>{1,2,4,5,6};
var even = list.Where(m => m%2 == 0);
list.Add(8);
foreach (var i in even)
{
    Console.WriteLine(i);
}

Output: 2, 4, 6, 8

Why not 2, 4, 6?

推荐答案

The output is 2,4,6,8 because of deferred execution.

The query is actually executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution.

-- Suprotim Agarwal, "Deferred vs Immediate Query Execution in LINQ"

There is another execution called Immediate Query Execution, which is useful for caching query results. From Suprotim Agarwal again:

To force immediate execution of a query that does not produce a singleton value, you can call the ToList(), ToDictionary(), ToArray(), Count(), Average() or Max() method on a query or query variable. These are called conversion operators which allow you to make a copy/snapshot of the result and access is as many times you want, without the need to re-execute the query.

If you want the output to be 2,4,6, use .ToList():

var list = new List<int>{1,2,4,5,6};
var even = list.Where(m => m%2 == 0).ToList();
list.Add(8);
foreach (var i in even)
 {
    Console.WriteLine(i);
 }

.net相关问答推荐

将Visual Studio更新到v17.9.3后,IDE关闭,dotnet.exe命令报告致命错误.内部CLR错误.(0x80131506)

如何在AutoMapper中添加自定义方法到项目中?

如何按需计算一个值并将该值缓存在FP/F#中?

.NET Core 中的微服务

如何手动注入依赖注入

如何在 Raspberry Pi 上托管 WASM 文件?

在.NET C#中截断整个单词的字符串

在 C# 中输入按键

整个命名空间的SuppressMessage

在一个 LINQ 查询中获取两列的总和

找不到 Microsoft.Office.Interop Visual Studio

调用委托与方法的性能

将跟踪输出重定向到控制台

何时使用抽象类?

析构函数、dispose 和 finalize 方法的区别

如何对 LINQ to XML 中的元素进行深层复制?

如何从头开始以编程方式配置 log4net(无配置)

如何在 C# 中处理 XML

如何判断uri字符串是否有效

如何修改 KeyValuePair 值?