c# - 这两种说法有什么区别?

标签 c# .net linq lambda

List<int> result1 = 
        (from number in list where number < 3 select number).ToList();

List<int> result2 = list.Where(n => n<3).ToList();

这两种不同的说法有什么区别?

最佳答案

第一种表示法通常称为“查询语法”,第二种表示法称为“方法语法”(或点表示法或 lambda 语法)——两者都被编译成完全相同的代码,但正如已经提到的,通常两者中的一个更简洁,对于大多数情况,这是点表示法,但特别是对于多个枚举的连接或分组查询语法真的很出色。

另请查看 LINQ Query Syntax versus Method Syntax (C#) :

Most queries in the introductory LINQ documentation are written as query expressions by using the declarative query syntax introduced in C# 3.0. However, the .NET common language runtime (CLR) has no notion of query syntax in itself. Therefore, at compile time, query expressions are translated to something that the CLR does understand: method calls. These methods are called the standard query operators, and they have names such as Where, Select, GroupBy, Join, Max, Average, and so on. You can call them directly by using method syntax instead of query syntax.

In general, we recommend query syntax because it is usually simpler and more readable; however there is no semantic difference between method syntax and query syntax.

关于c# - 这两种说法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347346/

相关文章:

c# - C# 和 R 的 Gzip 字节数组不同

c# - 为什么对象没有更新为 NULL

c# - Threading.Timer 在控制台应用程序中停止

.net - 将 HashSet<T> 转换为 .NET 中的数组

c# - 通过相同的值从另一个连接的 DataTable 更新 DataTable 的多列

linq - 如何在 dbml 文件中动态创建类

c# - MSDN 上 SimplePriorityQueue 示例中的严重错误

javascript - 如何在 SignalR 上获取已连接客户端的列表

c# - 在 Visual Studio 中使用 Windows 身份验证服务进行客户端开发

c# - LINQ 沿着对象树查询需要匹配的值