在LINQ查询表达式和表达方法之间的区别? [英] Difference between Query Expression and Method Expression in LINQ?

查看:249
本文介绍了在LINQ查询表达式和表达方法之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道以上职称的期限是否合适。

I don't know whether the term of above title is appropriate.

就像 A b

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);

当我应该使用每个人?而且任何区别吗?

When should I use each of them? And any difference?

推荐答案

无,查询表达式被编译成方法表达。

None, Query expression compiles into Method expression.

查询语法和方法语法在LINQ (C#)

由于查询返回一个IEnumerable,您可以通过链接的方法调用撰写他们的方法
语法一起。这是
编译器做什么幕后当您使用查询语法

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查询表达式(C#编程指南)

在编译时,查询表达式转换为标准的查询操作方法调用根据在C#
规范所规定的规则。可以通过使用查询语法
来表示的任何查询也可以通过使用方法语法表示。然而,在大多数情况下,
查询语法更易读和简洁。欲了解更多信息,请参阅
C#语言规范和标准查询运算符概述。

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.

除此之外,一个地方,我发现一些不能在查询表达式要做的就是相处指数与项目。例如,你可以做以下的方法的语法:

Apart from that one place where I have found something that can't be done in Query expression is to get the index along with the item. For example you can do following in method syntax:

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

在查询表达式的外部变量被定义来实现这一目的。下面是从乔恩斯基特

In query expression an external variable has to be defined to achieve this purpose. Here is a similar discussion with answer from Jon Skeet

这篇关于在LINQ查询表达式和表达方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆