Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET framework component that adds native data querying abilities to .NET languages, originally released as a major part of .NET Framework 3.5 and C# 3.0 in 2007.
LINQ extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources. Other uses, which utilize query expressions as a general framework for readably composing arbitrary computations, include the construction of event handlers or monadic parsers. It also defines a set of method names (called standard query operators, or standard sequence operators), along with translation rules used by the compiler to translate query syntax expressions into expressions using fluent-style (called method syntax by Microsoft) with these method names, lambda expressions and anonymous types.
Contents
Architecture
Standard query operator API
In what follows, the descriptions of the operators are based on the application of working with collections. Many of the operators take other functions as arguments. These functions may be supplied in the form of a named method or anonymous function.
The set of query operators defined by LINQ is exposed to the user as the Standard Query Operator (SQO) application programming interface (API). The query operators supported by the API are:
The Select operator performs a projection on the collection to select interesting aspects of the elements. The user supplies an arbitrary function, in the form of a named or lambda expression, which projects the data members. The function is passed to the operator as a delegate. This implements the Map higher-order function.
The Where operator allows the definition of a set of predicate rules that are evaluated for each object in the collection, while objects that do not match the rule are filtered away. The predicate is supplied to the operator as a delegate. This implements the Filter higher-order function.
For a user-provided mapping from collection elements to collections, semantically two steps are performed. First, every element is mapped to its corresponding collection. Second, the result of the first step is flattened by one level. Select and Where are both implementable in terms of SelectMany, as long as singleton and empty collections are available. The translation rules mentioned above still make it mandatory for a LINQ provider to provide the other two operators. This implements the Bind higher-order function.
These operators optionally take a function that retrieves a certain numeric value from each element in the collection and uses it to find the sum, minimum, maximum or average values of all the elements in the collection, respectively. Overloaded versions take no function and act as if the identity is given as the lambda.
A generalized Sum/Min/Max. This operator takes a function that specifies how two values are combined to form an intermediate or the final result. Optionally, a starting value can be supplied, enabling the result type of the aggregation to be arbitrary. Furthermore, a finalization function, taking the aggregation result to yet another value, can be supplied. This implements the Fold higher-order function.
Language extensions
While LINQ is mainly implemented as a library for .NET Framework 3.5, it also defines optional language extensions that make queries a first-class language construct and provide syntactic sugar for writing queries. These language extensions have initially been implemented in C# 3.0, VB 9.0, F# and Oxygene, with other languages like Nemerle having announced preliminary support. The language extensions include:
Query syntax: A language is free to choose a query syntax that it will recognize natively. These language keywords must be translated by the compiler to appropriate LINQ method calls.
Implicitly typed variables: This enhancement allows variables to be declared without specifying their types. The languages C# 3.0 and Oxygene declare them with the var keyword. In VB9.0, the Dim keyword without type declaration accomplishes the same. Such objects are still strongly typed; for these objects the compiler infers the types of variables via type inference, which allows the results of the queries to be specified and defined without declaring the type of the intermediate variables.
Anonymous types: Anonymous types allow classes that contain only data-member declarations to be inferred by the compiler. This is useful for the Select and Join operators, whose result types may differ from the types of the original objects. The compiler uses type inference to determine the fields contained in the classes and generates accessors and mutators for these fields.
Object initializer: Object initializers allow an object to be created and initialized in a single scope, as required for Select and Join operators.
Lambda expressions: Lambda expressions allow predicates and other projection functions to be written inline with a concise syntax, and support full lexical closure. They are captured into parameters as delegates or expression trees depending on the Query Provider.
For example, in the query to select all the objects in a collection with SomeProperty less than 10,
LINQ providers
The C#3.0 specification defines a Query Expression Pattern along with translation rules from a LINQ expression to an expression in a subset of C# 3.0 without LINQ expressions. The translation thus defined is actually un-typed, which, in addition to lambda expressions being interpretable as either delegates or expression trees, allows for a great degree of flexibility for libraries wishing to expose parts of their interface as LINQ expression clauses. For example, LINQ to Objects works on
System.Collections.Generic.IEnumerable<T>s and with delegates, whereas LINQ to SQL makes use of the expression trees.
The expression trees are at the core of the LINQ extensibility mechanism, by which LINQ can be adapted for many data sources. The expression trees are handed over to LINQ Providers, which are data source-specific implementations that adapt the LINQ queries to be used with the data source. If they choose so, the LINQ Providers analyze the expression trees contained in a query in order to generate essential pieces needed for the execution of a query. This can be SQL fragments or any other completely different representation of code as further manipulatable data.
LINQ comes with LINQ Providers for in-memory object collections, Microsoft SQL Server databases, ADO.NET datasets and XML documents. These different providers define the different flavors of LINQ:
The LINQ to Objects provider is used for in-memory collections, using the local query execution engine of LINQ. The code generated by this provider refers to the implementation of the standard query operators as defined on the Sequence pattern and allows System.Collections.Generic.IEnumerable<T> collections to be queried locally. Current implementation of LINQ to Objects perform interface implementation checks to allow for fast membership tests, counts, and indexed lookup operations when they are supported by the runtime type of the System.Collections.Generic.IEnumerable<T>.
The LINQ to XML provider converts an XML document to a collection of System.Linq.Xml.XElement objects, which are then queried against using the local execution engine that is provided as a part of the implementation of the standard query operator.
Performance
Non-professional users may struggle with subtleties in the LINQ to Objects features and syntax. Naive LINQ implementation patterns can lead to a catastrophic degradation of performance.
LINQ to XML and LINQ to SQL performance compared to ADO.NET depends on the use case.
PLINQ
Version 4 of the .NET framework includes Parallel Extensions for Parallel LINQ (PLINQ), a parallel execution engine for LINQ queries. It defines the System.Linq.ParallelQuery<T> class. Any implementation of the System.Collections.Generic.IEnumerable<T> interface can take advantage of the PLINQ engine by calling the AsParallel<T>(this IEnumerable<T>) extension method defined by the System.Linq.ParallelEnumerable class namespace of the .NET framework. The PLINQ engine can execute parts of a query concurrently on multiple threads, providing faster results.
Predecessor languages
Many of the concepts that LINQ introduced were originally tested in Microsoft's Cω research project, formerly known by the codenames X# (X Sharp) and Xen. It was renamed to Cω after Polyphonic C# (another research language based on join calculus principles) was integrated into it.
Cω attempts to make datastores (such as databases and XML documents) accessible with the same ease and type safety as traditional types like strings and arrays. Many of these ideas were inherited from an earlier incubation project within the WebData XML team called X# and Xen. Cω also includes new constructs to support concurrent programming; these features were largely derived from the earlier Polyphonic C# project.
First available in 2004 as a compiler preview, Cω's features were subsequently used by Microsoft in the creation of the LINQ features released in 2007 in .NET version 3.5 The concurrency constructs have also been released in a slightly modified form as a library, named Joins Concurrency Library, for C# and other .NET languages by Microsoft Research.




