gpt4 book ai didi

c# - LINQ 中查询表达式和方法表达式的区别?

转载 作者:IT王子 更新时间:2023-10-29 04:34:19 26 4
gpt4 key购买 nike

不知道上面的标题用词是否合适。

就像ab:

var list = Enumerable.Range(0, 100);

var a = from l in list
where l % 2 == 0
select l;
var b = list.Where(l => l % 2 == 0);

我应该什么时候使用它们?有什么区别吗?

最佳答案

无,Query 表达式编译成 Method 表达式。

Query Syntax and Method Syntax in LINQ (C#)

Because queries return an IEnumerable, you compose them in method syntax by chaining the method calls together. This is what the compiler does behind the scenes when you write queries by using query syntax

另见:LINQ Query Expressions (C# Programming Guide)

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise. For more information, see C# Language Specification and Standard Query Operators Overview.

除了我发现无法在查询表达式中完成的那个地方之外,就是获取索引和项目。例如,您可以在方法语法中执行以下操作:

var result = list.Select((r,i) => new { value = r, index = i});

在查询表达式中,必须定义一个外部变量来实现这个目的。这是与 answer from Jon Skeet 的类似讨论

关于c# - LINQ 中查询表达式和方法表达式的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15677958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com