C# 什么是 LINQ,它有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/471502/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:42:16  来源:igfitidea点击:

What is LINQ and what does it do?

c#linq

提问by Kredns

What is LINQ? I know it's for databases, but what does it do?

什么是LINQ?我知道它用于数据库,但它有什么作用?

采纳答案by Amy B

LINQstands for Language Integrated Query.

LINQ代表语言集成查询

Instead of writing YAQL (Yet Another Query Language), Microsoft language developers provided a way to express queries directly in their languages (such as C# and Visual Basic). The techniques for forming these queries do not rely on the implementation details of the thing being queried, so that you can write valid queries against many targets (databases, in-memory objects, XML) with practically no consideration of the underlying way in which the query will be executed.

Microsoft 语言开发人员没有编写 YAQL(另一种查询语言),而是提供了一种直接用他们的语言(例如 C# 和 Visual Basic)表达查询的方法。形成这些查询的技术不依赖于被查询事物的实现细节,因此您可以针对许多目标(数据库、内存中对象、XML)编写有效的查询,而实际上无需考虑查询将被执行。

Let's start this exploration with the parts belonging to the .NET Framework (3.5).

让我们从属于 .NET Framework (3.5) 的部分开始这个探索。

  • LINQ To Objects - examine System.Linq.Enumerablefor query methods. These target IEnumerable<T>, allowing any typed loopable collection to be queried in a type-safe manner. These queries rely on compiled .NET methods, not Expressions.

  • LINQ To Anything - examine System.Linq.Queryablefor some query methods. These target IQueryable<T>, allowing the construction of Expression Trees that can be translated by the underlying implementation.

  • Expression Trees - examine System.Linq.Expressionsnamespace. This is code as data. In practice, you should be aware of this stuff, but don't really need to write code against these types. Language features (such as lambda expressions) can allow you to use various short-hands to avoid dealing with these types directly.

  • LINQ To SQL - examine the System.Data.Linqnamespace. Especially note the DataContext. This is a DataAccess technology built by the C# team. It just works.

  • LINQ To Entities - examine the System.Data.Objectsnamespace. Especially note the ObjectContext. This is a DataAccess technology built by the ADO.NET team. It is complex, powerful, and harder to use than LINQ To SQL.

  • LINQ To XML - examine the System.Xml.Linqnamespace. Essentially, people weren't satisfied with the stuff in System.Xml. So Microsoft re-wrote it and took advantage of the re-write to introduce some methods that make it easier to use LINQ To Objects against XML.

  • Some nice helper types, such as Funcand Action. These types are delegates with Generic Support. Gone are the days of declaring your own custom (and un-interchangable) delegate types.

  • LINQ To Objects - 检查System.Linq.Enumerable的查询方法。这些目标IEnumerable<T>,允许以类型安全的方式查询任何类型化的可循环集合。这些查询依赖于编译的 .NET 方法,而不是表达式。

  • LINQ To Anything - 检查System.Linq.Queryable以了解某些查询方法。这些目标IQueryable<T>,允许构建可由底层实现翻译的表达式树。

  • 表达式树 - 检查System.Linq.Expressions命名空间。这是代码即数据。在实践中,您应该了解这些内容,但实际上并不需要针对这些类型编写代码。语言特性(例如 lambda 表达式)可以让您使用各种简写来避免直接处理这些类型。

  • LINQ To SQL - 检查System.Data.Linq命名空间。特别注意DataContext. 这是一种由 C# 团队构建的 DataAccess 技术。它只是有效。

  • LINQ To Entities - 检查System.Data.Objects命名空间。特别注意ObjectContext. 这是 ADO.NET 团队构建的 DataAccess 技术。它比 LINQ To SQL 复杂、强大且更难使用。

  • LINQ To XML - 检查System.Xml.Linq命名空间。本质上,人们对System.Xml. 所以微软重新编写了它,并利用重新编写的优势引入了一些方法,可以更容易地针对 XML 使用 LINQ To Objects。

  • 一些不错的辅助类型,例如FuncAction。这些类型是具有通用支持的委托。声明自己的自定义(且不可互换)委托类型的日子已经一去不复返了。

All of the above is part of the .NET Framework, and available from any .NET language (VB.NET, C#, IronPython, COBOL .NET etc).

以上所有内容都是 .NET Framework 的一部分,可用于任何 .NET 语言(VB.NET、C#、IronPython、COBOL .NET 等)。



Ok, on to language features. I'm going to stick to C#, since that's what I know best. VB.NET also had several similar improvements (and a couple that C# didn't get - XML literals). This is a short and incomplete list.

好的,关于语言功能。我将坚持使用 C#,因为这是我最了解的。VB.NET 也有几个类似的改进(还有一些 C# 没有得到 - XML 文字)。这是一个简短且不完整的列表。

  • Extension Methods - this allows you to "add" a method to type. The method is really a static method that is passed an instance of the type, and is restricted to the public contract of the type, but it very useful for adding methods to types you don't control (string), or adding (fully implemented) helper methods to interfaces.

  • Query Comprehension Syntax - this allows you to write in a SQL Like structure. All of this stuff gets translated to the methods on System.Linq.Queryable or System.Linq.Enumerable (depending on the Type of myCustomers). It is completely optional and you can use LINQ well without it. One advantage to this style of query declaration is that the range variables are scoped: they do not need to be re-declared for each clause.

    IEnumerable<string> result =
     from c in myCustomers
     where c.Name.StartsWith("B")
     select c.Name;
    
  • Lambda Expressions - This is a shorthand for specifying a method. The C# compiler will translate each into either an anonymous method or a true System.Linq.Expressions.Expression. You really need to understand these to use Linq well. There are three parts: a parameter list, an arrow, and a method body.

    IEnumerable<string> result = myCustomers
     .Where(c => c.Name.StartsWith("B"))
     .Select(c => c.Name);`
    
  • Anonymous Types - Sometimes the compiler has enough information to create a type for you. These types aren't truly anonymous: the compiler names them when it makes them. But those names are made at compile time, which is too late for a developer to use that name at design time.

    myCustomers.Select(c => new 
    {
      Name = c.Name;
      Age = c.Age;
    })
    
  • Implicit Types - Sometimes the compiler has enough information from an initialization that it can figure out the type for you. You can instruct the compiler to do so by using the var keyword. Implicit typing is required to declare variables for Anonymous Types, since programmers may not use the name of an anonymoustype.

    // The compiler will determine that names is an IEnumerable<string>
    var names = myCustomers.Select(c => c.Name);
    
  • 扩展方法 - 这允许您“添加”要键入的方法。该方法实际上是传递类型实例的静态方法,并且仅限于类型的公共契约,但是对于向您不控制的类型(字符串)或添加(完全实现)的类型添加方法非常有用) 接口的辅助方法。

  • 查询理解语法 - 这允许您编写类似 SQL 的结构。所有这些内容都被转换为 System.Linq.Queryable 或 System.Linq.Enumerable 上的方法(取决于 myCustomers 的类型)。它是完全可选的,没有它您也可以很好地使用 LINQ。这种查询声明风格的一个优点是范围变量是有作用域的:不需要为每个子句重新声明它们。

    IEnumerable<string> result =
     from c in myCustomers
     where c.Name.StartsWith("B")
     select c.Name;
    
  • Lambda 表达式 - 这是指定方法的简写。C# 编译器会将每个转换为匿名方法或 true System.Linq.Expressions.Expression。你真的需要了解这些才能很好地使用 Linq。共有三部分:参数列表、箭头和方法体。

    IEnumerable<string> result = myCustomers
     .Where(c => c.Name.StartsWith("B"))
     .Select(c => c.Name);`
    
  • 匿名类型 - 有时编译器有足够的信息来为你创建一个类型。这些类型并不是真正匿名的:编译器在生成它们时命名它们。但是这些名称是在编译时生成的,开发人员在设计时使用该名称为时已晚。

    myCustomers.Select(c => new 
    {
      Name = c.Name;
      Age = c.Age;
    })
    
  • 隐式类型 - 有时编译器从初始化中获得足够的信息,可以为您找出类型。您可以使用 var 关键字指示编译器这样做。隐式类型需要为匿名类型声明变量,因为程序员可能不会使用匿名类型的名称。

    // The compiler will determine that names is an IEnumerable<string>
    var names = myCustomers.Select(c => c.Name);
    

回答by Jobo

http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

"The LINQ Project is a codename for a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities."

“LINQ 项目是 .NET Framework 的一组扩展的代号,其中包含语言集成的查询、设置和转换操作。它使用用于查询的本机语言语法扩展了 C# 和 Visual Basic,并提供了类库以利用这些能力。”

回答by Jeffrey Hantin

LINQ (Language INtegrated Query) may refer to:

LINQ(语言集成查询)可以指:

  • a library for collection and iterator manipulation that makes extensive use of higher-order functions as arguments (System.Linq)

  • a library for passing and manipulation of simple functions as abstract syntax trees (System.Linq.Expressions)

  • a syntax extension to various languages to provide a more SQL-like syntax for processing collections, a more compact notation for anonymous functions, and a mechanism to introduce static helper functions syntactically indistinguishable from final member functions

  • an interface definition to which data providers may conform in order to receive query structure and potentially perform optimization thereon, or occasionally the compatible data providers themselves

  • 一个用于集合和迭代器操作的库,它广泛使用高阶函数作为参数(System.Linq)

  • 用于将简单函数作为抽象语法树传递和操作的库(System.Linq.Expressions)

  • 对各种语言的语法扩展,为处理集合提供更像 SQL 的语法,匿名函数的更紧凑符号,以及引入静态辅助函数的机制,在语法上与最终成员函数无法区分

  • 数据提供者可能遵循的接口定义,以便接收查询结构并可能对其执行优化,或者有时兼容的数据提供者本身

The components may be used in isolation or combined.

这些组件可以单独使用或组合使用。

回答by Vojislav Stojkovic

In a nutshell, LINQ (Language-Integrated Query) allows you to write queries directly in your code. Those queries can be on relational databases, but also on XML or in-memory container objects, such as arrays and lists. More information is available in MSDN library: http://msdn.microsoft.com/en-us/library/bb308959.aspx

简而言之,LINQ(语言集成查询)允许您直接在代码中编写查询。这些查询可以针对关系数据库,也可以针对 XML 或内存中的容器对象,例如数组和列表。MSDN 库中提供了更多信息:http: //msdn.microsoft.com/en-us/library/bb308959.aspx

回答by jcollum

I'm gonna try for a simple answer: LINQ is a way for you to query your database (or other datastore, XML etc) using a query language that is similar to SQL but can be compiled inside a .NET application.

我将尝试一个简单的答案:LINQ 是一种让您使用类似于 SQL 但可以在 .NET 应用程序中编译的查询语言来查询数据库(或其他数据存储、XML 等)的方法。

回答by Mark Brackett

LINQ stands for Language Integrated Query, and is a way of providing a general purpose "querying" mechanism in the CLR.

LINQ 代表语言集成查询,是一种在 CLR 中提供通用“查询”机制的方式。

At it's most basic level, this consists of a set of methods on IEnumerable<T> - eg., Select, Sum, Where - that can be used for restrictions, projections, etc.[1]

在最基本的层面上,这包括 IEnumerable<T> 上的一组方法 - 例如,Select、Sum、Where - 可用于限制、投影等[1]

To take it a bit further, LINQ also defines a new LINQ provider model that can take an expression tree and use it to run "native" queries against a datasource outside of the CLR - eg., LINQ to SQL, LINQ to XML, LINQ to NHibernate, etc.

更进一步,LINQ 还定义了一个新的 LINQ 提供程序模型,该模型可以采用表达式树并使用它对 CLR 之外的数据源运行“本机”查询 - 例如,LINQ to SQL、LINQ to XML、LINQ到 NHibernate 等。

C# and VB.NET have also defined a query syntax that allows you to write strongly typed queries inline (that looks very similar to SQL), which the compiler then translates into the equivalent IEnumerable<T> calls.

C# 和 VB.NET 还定义了一种查询语法,允许您内联编写强类型查询(看起来与 SQL 非常相似),然后编译器将其转换为等效的 IEnumerable<T> 调用。

To me, the most interesting thing about LINQ is all of the C# and VB.NET features that were needed to support it are useful in their own right. Extension methods, anonymous types, lambda expressions, and implicit typing were all required to support LINQ - but we tend to use those features outside of a pure LINQ context.

对我来说,关于 LINQ 最有趣的事情是支持它所需的所有 C# 和 VB.NET 功能本身就很有用。扩展方法、匿名类型、lambda 表达式和隐式类型都是支持 LINQ 所必需的——但我们倾向于在纯 LINQ 上下文之外使用这些功能。

[1] Those are relational terms, functional programmers would probably prefer Map, Reduce, Fold, etc.

[1] 这些是关系术语,函数式程序员可能更喜欢 Map、Reduce、Fold 等。

回答by Mark Brittingham

LINQ is a technology for extracting data using an idiom derived from the C# programming language. While it owes much in functional design to SQL, it is fundamentally its own data querying language. It operates across a broad spectrum of data sources (SQL databases, in-memory representations, XML, etc.). LINQ-To-SQL, in particular, should be seen as a contrast to the traditional use of embedded SQL which suffers from what is often referred to as an "impedance mismatch" between the SQL programming and C#/VB programming.

LINQ 是一种使用源自 C# 编程语言的习语提取数据的技术。虽然它在功能设计上很大程度上归功于 SQL,但它基本上是它自己的数据查询语言。它跨广泛的数据源(SQL 数据库、内存中表示、XML 等)运行。LINQ-To-SQL 尤其应该被视为与嵌入式 SQL 的传统使用形成对比,后者遭受 SQL 编程和 C#/VB 编程之间通常被称为“阻抗不匹配”的困扰。

For a discussion of LINQ and its limitations, you may want to take a look at this related question: Doesn't LINQ to SQL miss the point?

对于 LINQ 及其局限性的讨论,您可能想看看这个相关的问题:LINQ to SQL 是否没有抓住重点?