c# - Where 方法如何运行?

标签 c# linq lambda

我的 code是:

using System;
using System.Linq;
using System.Collections.Generic;

public class D {
   public string Value { get; set; }
   public D(string v) { this.Value = v; }
}
public class Program
{
   public static void Main()
   {
       List<D> DD = new List<D>();
       DD.Add(new D("2018-11-08"));
       DD.Add(new D("2018-12-01"));
       var dd = DD.Where(d=> { 
          Console.WriteLine($"In predicate: {d.Value}"); 
          return d.Value=="2018-12-01"; 
       });

       var dl = dd.ToList();
       foreach (var d in dl) {
         Console.WriteLine($"Final: {d.Value}");
       }
   }
}

输出是:

In predicate: 2018-11-08
In predicate: 2018-12-01
Final: 2018-12-01

如果DD包含100万个元素,DD.Where中的lambda会执行100万次吗?

如果 DD 是来自 SQL Server 的表怎么办?

最佳答案

If DD contains 1 million elements, will the lambda in DD.Where execute 1 million times?

答案取决于急切操作。在这种特定情况下,因为急切的操作是ToList,但说它是First()Any()一旦找到符合条件的元素,它就会短路。

关于c# - Where 方法如何运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206922/

相关文章:

java - 在 Groovy 1.x 中编写 Java8 Lambda

c++ - 如何摆脱 lambda 语法

c# - 在 MVC 5 的 Controller 中访问声明值

c# - 在同一解决方案中添加 WCF 引用,而不添加服务引用

c# - '/' 应用程序中的服务器错误。 <asp :ToolkitScriptManager ID ="ToolkitScriptManager1" runat ="server">

c# - IEnumerable.Count() O(n)

linq - 在 DocumentDb 中使用 ThenBy 显示错误

c# - 如何将 IEnumerable<object> 转换为 IEnumerable<runtime type>

c# - Linq to entity,使用不在运算符中的sql

Java流: one liner to perform multiple numeric operations on Int stream