visual-studio C# 中的 System.Linq.Expressions 是干什么用的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1427261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is System.Linq.Expressions in C# used for?
提问by yeeen
Is LINQ a new feature in .NET 4.0, unsupported in older versions like .NET 3.5? What is it useful for? It seems to be able to build Expression Trees. What is an Expression Tree, actually? Is LINQ able to extract info like class, method and field from a C# file?
LINQ 是 .NET 4.0 中的一项新功能,在 .NET 3.5 等旧版本中不受支持吗?它有什么用?它似乎能够构建表达式树。什么是表达式树?LINQ 是否能够从 C# 文件中提取类、方法和字段等信息?
Can someone provide me a working piece of code to demonstrate what LINQ can do?
有人可以向我提供一段工作代码来演示 LINQ 可以做什么吗?
采纳答案by Jeff Yates
LINQis a .NET 3.5 feature with built-in language support from C# 3.0 and Visual Basic 2008. There are plenty of examples on MSDN.
LINQ是 .NET 3.5 的一项功能,具有来自 C# 3.0 和 Visual Basic 2008 的内置语言支持。MSDN 上有大量示例。
回答by ShuggyCoUk
Linq was added in .Net 3.5 (and added to the c# 3.0 compiler as well as in slightly limited form to the VB.net compiler in the same release)
Linq 已添加到 .Net 3.5(并添加到 c# 3.0 编译器以及在同一版本中以稍微受限的形式添加到 VB.net 编译器)
In is language integrated query, though it covers many complex additions to both the language and the runtime in order to achieve this which are useful in and of themselves.
In is 语言集成查询,尽管它涵盖了语言和运行时的许多复杂添加,以实现这一点,这些添加本身很有用。
The Expression functionality is simply put the ability for a program, at runtime, inspect the abstract syntax of certain code constructs passed around. These are called lambdas. And are, in essence a way of writing anonymous functions more easily whilst making runtime introspection of their structure easier.
表达式功能只是让程序能够在运行时检查传递的某些代码结构的抽象语法。这些被称为 lambda。并且,本质上是一种更容易编写匿名函数的方式,同时使运行时对其结构的内省更容易。
The 'SQL like' functionality Linq is most closely associated with (though by no means the only one) is called Linq to Sql where by something like this:
与 Linq 最密切相关的“SQL 类”功能(尽管绝不是唯一的)被称为 Linq to Sql,其中类似于以下内容:
from f in Foo where s.Blah == "wibble" select f.Wobble;
is compiled into a representation of this query, rather than simply code to executethe query. The part that makes it linq to sql is the 'backend' which converts it into sql. For this the expression is translated into sql server statements to execute the query against a linked database with mapping from rows to .net objects and conversion of the c# logic into equivalent where clauses. You could apply exactly the same code if Foo was a collection of plain .net objects (at which point it is "Linq to objects") the conversion of the expression would then be to straight .Net code.
被编译成这个查询的表示,而不是简单的代码来执行查询。使其 linq 到 sql 的部分是将其转换为 sql 的“后端”。为此,表达式被转换为 sql server 语句,以通过从行到 .net 对象的映射以及将 c# 逻辑转换为等效的 where 子句,对链接数据库执行查询。如果 Foo 是一个普通 .net 对象的集合(此时它是“Linq to objects”),您可以应用完全相同的代码,然后表达式的转换将是直接的 .Net 代码。
The lambda above written in the language integrated way is actually the equivalent of:
上面用语言集成方式写的 lambda 实际上相当于:
Foo.Where(f => f.Blah == "wibble).Select(f => f.Wobble);
Foo.Where(f => f.Blah == "wibble).Select(f => f.Wobble);
Where Foo is a typed collection. For databases classes are synthesized to represent the values in the database to allow this to both compile, and to allow round tripping values from the sql areas to the .net areas and vice versa.
其中 Foo 是类型化集合。对于数据库类被合成来表示数据库中的值,以允许编译,并允许从 sql 区域到 .net 区域的往返值,反之亦然。
The critical aspect of the Language Integratedpart of Linq is that the resulting language constructs are first class parts of the resulting code. Rather than simply resulting in a function they provide the way the function was constructed (as an expression) so that other aspects of the program can manipulate it.
Linq的语言集成部分的关键方面是生成的语言结构是生成代码的第一类部分。它们不是简单地生成一个函数,而是提供了构造函数的方式(作为表达式),以便程序的其他方面可以操作它。
Consumers of this functionality may simply chose to run it (execute the function which the lambda is compiled to) or to ask for the expression which describes it and then do something different with it.
此功能的使用者可以简单地选择运行它(执行 lambda 被编译成的函数)或要求描述它的表达式,然后用它做一些不同的事情。
Many aspects of what makes this possible are placed under the "Linq" banner despite not really being Linq themsleves.
For example anonymous types are required for easy use of projection(choosing a subset of the possible properties) but anonymous types can be used outside of Linq as well.
尽管不是真正的 Linq 本身,但使这成为可能的许多方面都放在“Linq”的旗帜下。
例如,为了便于使用projection(选择可能属性的子集)需要匿名类型,但匿名类型也可以在 Linq 之外使用。
Linq, especially via the lambdas (which make writing anonymous delegates very lightweight in terms of syntax) has lead to an increase in the functional capabilities of c#. this is reinforced by the extension methods on IEnumerable<T>like Select(), corresponding to mapin many function languages and Where() corresponding to filter. Like the anonymous types this is not in and of itself "Linq" though is viewed by many as a strongly beneficial effect on c# development (this is not a universal view but is widely held).
Linq,尤其是通过 lambdas(这使得编写匿名委托在语法方面非常轻量级)导致了 c# 功能的增加。这通过IEnumerable<T>像 Select() 这样的扩展方法得到加强,对应map于许多函数语言和 Where() 对应于filter. 就像匿名类型一样,这本身并不是“Linq”,尽管许多人认为它对 c# 开发有很大的好处(这不是普遍的观点,但被广泛接受)。
- For an introduction to Linq from microsoft read this article
- For an introduction to how to use Linq-to-Sql in Visual Studio see this series from Scott Guthrie
- For a guide to how you can use linq to make plain c# easier when using collections read this article
- 有关微软对 Linq 的介绍,请阅读这篇文章
- 有关如何在 Visual Studio 中使用 Linq-to-Sql 的介绍,请参阅Scott Guthrie 的这个系列
- 有关如何在使用集合时使用 linq 使纯 c# 变得更容易的指南,请阅读本文
Expressions are a more advanced topic, and understanding of them is entirely unecessary to uselinq, though certain 'tricks' are possible using them. In general you would care about Expressions only if you were attempting to write linq providers which is code to take an expression rather than just a function and use that to do something other than what the plain function would do, like talk to an external data source.
表达式是一个更高级的主题,使用linq完全不需要理解它们,尽管使用它们可能会有某些“技巧”。一般来说,只有当您尝试编写 linq 提供程序时,您才会关心表达式,该提供程序是获取表达式的代码,而不仅仅是一个函数,并使用它来执行普通函数以外的其他操作,例如与外部数据源交谈.
- Here are some Linq Provider examples
- A multi part guide to implementing your own provider
- The MDSN documentation for the namespace
Other uses would be when you wish to get some meta data about what the internals of the function is doing, perhaps then compiling the expression (resulting in a delegate which will allow you to execute the expression as a function) and doing something with it or just looking at the metadata of the objects to do reflective code which is compile time verified as this answer shows.
其他用途是当您希望获得一些关于函数内部正在做什么的元数据时,也许然后编译表达式(产生一个委托,允许您将表达式作为函数执行)并用它做一些事情或只是查看对象的元数据来执行反射代码,编译时验证如此答案所示。
回答by Ty.
One area of this question that hasn't been covered yet is expression trees. There is a really good article on expression trees (and lambda expression) available here.
这个问题中尚未涉及的一个领域是表达式树。有对表达式树(和lambda表达式)提供一个很好的文章在这里。
The other important thing to bring up about expression trees is that by building an expression tree to define what you aregoing to do, you don't have to actuallydo anything. I am referring to deferred execution.
带来了约表达式树的另一个重要的事情是,通过建立一个表达式树来定义你什么都要做的事情,你没有真正做任何事情。我指的是延迟执行。
//this code will only build the expression tree
var itemsInStock = from item in warehouse.Items
where item.Quantity > 0;
// this code will cause the actual execution
Console.WriteLine("Items in stock: {0}", itemsInStock.Count());
回答by RaYell
回答by Dan Esparza
This is also covered pretty extensively here on SO.
回答by Steve Severance
System.Linq.Expressions is for hand building (or machine generating) expression trees. I have a feeling that given the complexity of building more complicated functionality that this namespace is under used. However it is exceedingly powerful. For instance one of my co workers recently implemented an expression tree that can auto scale any LINQ to SQL object using a cumultive density function. Every column gets its own tree that gets compiled so its fast. I have been building a specialized compiler that uses them extensively to implement basic functionality as well as glue the rest of the generated code together.
System.Linq.Expressions 用于手工构建(或机器生成)表达式树。我有一种感觉,考虑到构建更复杂的功能的复杂性,这个命名空间正在使用中。然而它的威力却是无比的强大。例如,我的一位同事最近实现了一个表达式树,它可以使用 cumultive 密度函数自动缩放任何 LINQ to SQL 对象。每列都有自己的树,编译速度很快。我一直在构建一个专门的编译器,它广泛地使用它们来实现基本功能并将生成的代码的其余部分粘合在一起。
Please see this blog postfor more information and ideas.
请参阅此博客文章以获取更多信息和想法。
回答by JayJay
Here is a lot of Linq-examples:
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
这里有很多 Linq 示例:http:
//msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

