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/