Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Language Integrated Query

From Wikipedia, the free encyclopedia
(Redirected from)
Microsoft .NET Framework component
"LINQ" redirects here. For other uses, seeLinq (disambiguation).
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This articlecontainsinstructions or advice. Wikipedia is not a guidebook; please helprewrite such content to be encyclopedic or move it toWikiversity,Wikibooks, orWikivoyage.(September 2024)
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Language Integrated Query" – news ·newspapers ·books ·scholar ·JSTOR
(September 2024) (Learn how and when to remove this message)
(Learn how and when to remove this message)
Language Integrated Query
Designed byMicrosoft Corporation
DeveloperMicrosoft Corporation
Typing disciplineStrongly typed
Websitehttps://learn.microsoft.com/en-us/dotnet/standard/linq/
Majorimplementations
.NET languages (C#,F#,VB.NET)
Influenced by
SQL,Haskell

Language Integrated Query (LINQ, pronounced "link") is aMicrosoft.NET Framework component that adds native dataquerying capabilities to.NET languages, originally released as a major part of.NET Framework 3.5 in 2007.

LINQ extends the language by the addition of queryexpressions, which are akin toSQL statements, and can be used to conveniently extract and process data fromarrays, enumerableclasses,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[1] ormonadicparsers.[2] It also defines a set of method names (calledstandard query operators, orstandard sequence operators), along with translation rules used by the compiler to translate query syntax expressions into expressions usingfluent-style (called method syntax by Microsoft) with these method names,lambda expressions andanonymous types.

Architecture

[edit]

Standard query operator API

[edit]

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 queryoperators defined by LINQ is exposed to the user as the Standard Query Operator (SQO)API. The query operators supported by the API are:[3]

Select
The Select operator performs aprojection on the collection to select interesting aspects of the elements. The user supplies an arbitrary function, in the form of a named orlambda expression, which projects the data members. The function is passed to the operator as adelegate. This implements theMap higher-order function.
Where
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 theFilter higher-order function.
SelectMany
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 thebind higher-order function.
Sum / Min / Max / Average

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.

Aggregate

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 implement theFold higher-order function.

Join / GroupJoin
The Join operator performs aninner join on two collections, based on matching keys for objects in each collection. It takes two functions as delegates, one for each collection, that it executes on each object in the collection to extract the key from the object. It also takes another delegate in which the user specifies which data elements, from the two matched elements, should be used to create the resultant object. The GroupJoin operator performs agroup join. Like the Select operator, the results of a join are instantiations of a different class, with all the data members of both the types of the source objects, or a subset of them.
Take / TakeWhile
The Take operator selects the first n objects from a collection, while the TakeWhile operator, which takes a predicate, selects those objects that match the predicate (stopping at the first object that doesn't match it).
Skip / SkipWhile
The Skip and SkipWhile operators are complements of Take and TakeWhile - they skip the first n objects from a collection, or those objects that match a predicate (for the case of SkipWhile).
OfType
The OfType operator is used to select the elements of a certain type.
Concat
The Concat operatorconcatenates two collections.
OrderBy / ThenBy
The OrderBy operator is used to specify the primary sort ordering of the elements in a collection according to some key. The default ordering is in ascending order, to reverse the order, theOrderByDescending operator is to be used. ThenBy andThenByDescending specifies subsequent ordering of the elements. The function to extract the key value from the object is specified by the user as a delegate.
Reverse
The Reverse operator reverses a collection.
GroupBy
The GroupBy operator takes a function that extracts a key value and returns a collection ofIGrouping<Key, Values> objects, for each distinct key value. TheIGrouping objects can then be used to enumerate all the objects for a particular key value.
Distinct
The Distinct operator removes duplicate instances of an object from a collection. An overload of the operator takes an equality comparer object which defines the criteria for distinctness.
Union / Intersect / Except
These operators are used to perform aunion,intersection anddifference operation on two sequences, respectively. Each has an overload which takes an equality comparer object which defines the criteria for element equality.
SequenceEqual
The SequenceEqual operator determines whether all elements in two collections are equal and in the same order.
First / FirstOrDefault / Last / LastOrDefault
These operators take a predicate. The First operator returns the first element for which the predicate yields true, or, if nothing matches, throws an exception. The FirstOrDefault operator is like the First operator except that it returns the default value for the element type (usually a null reference) in case nothing matches the predicate. The last operator retrieves the last element to match the predicate, or throws an exception in case nothing matches. The LastOrDefault returns the default element value if nothing matches.
Single
The Single operator takes a predicate and returns the element that matches the predicate. An exception is thrown, if none or more than one element match the predicate.
SingleOrDefault
The SingleOrDefault operator takes a predicate and return the element that matches the predicate. If more than one element matches the predicate, an exception is thrown. If no element matches the predicate, a default value is returned.
ElementAt
The ElementAt operator retrieves the element at a given index in the collection.
Any / All
The Any operator checks, if there are any elements in the collection matching the predicate. It does not select the element, but returns true if at least one element is matched. An invocation of any without a predicate returns true if the collection non-empty. The All operator returns true if all elements match the predicate.
Contains
The Contains operator checks, if the collection contains a given element.
Count
The Count operator counts the number of elements in the given collection. An overload taking a predicate, counts the number of elements matching the predicate.

The standard query operator API also specifies certain operators that convert a collection into another type:[3]

  • AsEnumerable: Statically types the collection as anIEnumerable<T>.[4]
  • AsQueryable: Statically types the collection as anIQueryable<T>.
  • ToArray: Creates an arrayT[] from the collection.
  • ToList: Creates aList<T> from the collection.
  • ToDictionary: Creates aDictionary<K, T> from the collection, indexed by the key K. A user supplied projection function extracts a key from each element.
  • ToLookup: Creates aLookup<K, T> from the collection, indexed by the key K. A user supplied projection function extracts a key from each element.
  • Cast: converts a non-genericIEnumerable collection to one ofIEnumerable<T> by casting each element to typeT. Alternately converts a genericIEnumerable<T> to another genericIEnumerable<R> by casting each element from typeT to typeR. Throws an exception in any element cannot be cast to the indicated type.
  • OfType: converts a non-genericIEnumerable collection to one ofIEnumerable<T>. Alternately converts a genericIEnumerable<T> to another genericIEnumerable<R> by attempting to cast each element from typeT to typeR. In both cases, only the subset of elements successfully cast to the target type are included. No exceptions are thrown.

Language extensions

[edit]

While LINQ is primarily implemented as alibrary for .NET Framework 3.5, it also defines optional language extensions that make queries a first-classlanguage construct and providesyntactic sugar for writing queries. These language extensions have initially been implemented inC# 3.0,[5]: 75 VB 9.0,F#[6] andOxygene, with other languages likeNemerle having announced preliminary support. The language extensions include:[7]

  • 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[5]: 367  and Oxygene declare them with thevar keyword. In VB9.0, theDim keyword without type declaration accomplishes the same. Such objects are stillstrongly typed; for these objects the compiler infers the types of variables viatype 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 generatesaccessors 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 withSomeProperty less than 10,

IEnumerable<MyObject>SomeCollection=/* something here */IEnumerable<MyObject>results=fromcinSomeCollectionwherec.SomeProperty<10selectnew{c.SomeProperty,c.OtherProperty};foreach(MyObjectresultinresults){Console.WriteLine(result);}

the types of variablesresult,c andresults all are inferred by the compiler in accordance to the signatures of the methods eventually used. The basis for choosing the methods is formed by the query expression-free translation result

IEnumerble<MyObject>results=SomeCollection.Where(c=>c.SomeProperty<10).Select(c=>new{c.SomeProperty,c.OtherProperty});results.ForEach(x=>{Console.WriteLine(x.ToString());})

LINQ providers

[edit]

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 onIEnumerable<T>s and with delegates, whereasLINQ 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:

LINQ to Objects

[edit]

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 theSequence pattern and allowsIEnumerable<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 IEnumerable.[8][9][10]

LINQ to XML (formerly called XLINQ)

[edit]

The LINQ to XML provider converts an XML document to a collection ofXElement 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.[11]

LINQ to SQL (formerly called DLINQ)

[edit]

The LINQ to SQL provider allows LINQ to be used to queryMicrosoft SQL Server databases, includingSQL Server Compact databases. Since SQL Server data may reside on a remote server, and because SQL Server has its own query engine, LINQ to SQL does not use the query engine of LINQ. Instead, it converts a LINQ query to aSQL query that is then sent to SQL Server for processing.[12] However, since SQL Server stores the data asrelational data and LINQ works with data encapsulated in objects, the two representations must bemapped to one another. For this reason, LINQ to SQL also defines a mapping framework. The mapping is done by defining classes that correspond to the tables in the database, and containing all or a subset of the columns in the table as data members.[13] The correspondence, along with otherrelational model attributes such asprimary keys, are specified using LINQ to SQL-definedattributes. For example,

[Table(Name="Customers")]publicclassCustomer{[Column(IsPrimaryKey = true)]publicintCustID;[Column]publicstringCustName;}

This class definition maps to a table namedCustomers and the two data members correspond to two columns. The classes must be defined before LINQ to SQL can be used.Visual Studio 2008 includes a mapping designer that can be used to create the mapping between the data schemas in the object as well as the relational domain. It can automatically create the corresponding classes from adatabase schema, as well as allow manual editing to create a different view by using only a subset of the tables or columns in a table.[13]

The mapping is implemented by theDataContext that takes a connection string to the server, and can be used to generate aTable<T> where T is the type to which the database table will be mapped. TheTable<T> encapsulates the data in the table, and implements theIQueryable<T> interface, so that the expression tree is created, which the LINQ to SQL provider handles. It converts the query intoT-SQL and retrieves the result set from the database server. Since the processing happens at the database server, local methods, which are not defined as a part of the lambda expressions representing the predicates, cannot be used. However, it can use thestored procedures on the server. Any changes to the result set are tracked and can be submitted back to the database server.[13]

LINQ to DataSets

[edit]

Since the LINQ to SQL provider (above) works only withMicrosoft SQL Server databases, in order to support any generic database, LINQ also includes the LINQ to DataSets. It uses ADO.NET to handle the communication with the database. Once the data is in ADO.NET Datasets, LINQ to DataSets execute queries against these datasets.[14]

Performance

[edit]
Parts of this article (those related to Performance) need to beupdated. The reason given is: The source is old and now performs better than before. Please help update this article to reflect recent events or newly available information.(November 2021)

Non-professional users may struggle with subtleties in theLINQ to Objects features and syntax. Naive LINQ implementation patterns can lead to a catastrophic degradation of performance.[15][16]

LINQ to XML andLINQ to SQL performance compared to ADO.NET depends on the use case.[17][18]

PLINQ

[edit]

Version 4 of the .NET framework includesPLINQ, orParallel LINQ, aparallel execution engine for LINQ queries. It defines theParallelQuery<T> class. Any implementation of theIEnumerable<T> interface can take advantage of the PLINQ engine by calling theAsParallel<T>(thisIEnumerable<T>) extension method defined by the ParallelEnumerable class in the System.Linq namespace of the .NET framework.[19] The PLINQ engine can execute parts of a query concurrently on multiple threads, providing faster results.[20]

Predecessor languages

[edit]

Many of the concepts that LINQ introduced were originally tested in Microsoft's research project, formerly known by thecodenamesX# (X Sharp) andXen. It was renamed to Cω afterPolyphonic C# (another research language based onjoin calculus principles) was integrated into it.

Cω attempts to make datastores (such asdatabases andXML documents) accessible with the same ease andtype safety as traditional types likestrings andarrays. 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 supportconcurrent programming; these features were largely derived from the earlier Polyphonic C# project.[21]

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[22] The concurrency constructs have also been released in a slightly modified form as a library, namedJoins Concurrency Library, forC# and other .NET languages byMicrosoft Research.[23]

Ports

[edit]

Ports of LINQ exist forPHP (PHPLinqArchived 2018-01-19 at theWayback Machine),JavaScript (linq.js),TypeScript (linq.ts), andActionScript (ActionLinqArchived 2018-12-25 at theWayback Machine), and C++ (CXXIter), although none are strictly equivalent to LINQ in the .NET inspired languages C#, F# and VB.NET (where it is a part of the language, not an external library, and where it often addresses a wider range of needs).[citation needed]

See also

[edit]

References

[edit]
  1. ^"Rx framework". 10 June 2011.
  2. ^"Monadic Parser Combinators using C#3". Retrieved2009-11-21.
  3. ^ab"Standard Query Operators". Microsoft. Retrieved2007-11-30.
  4. ^"Enumerable Class".msdn. Microsoft. Retrieved15 February 2014.
  5. ^abSkeet, Jon (23 March 2019).C# in Depth. Manning.ISBN 978-1617294532.
  6. ^"Query Expressions (F#)".Microsoft Docs. Retrieved2012-12-19.
  7. ^"LINQ Framework". Retrieved2007-11-30.
  8. ^"Enumerable.ElementAt". Retrieved2014-05-07.
  9. ^"Enumerable.Contains". Retrieved2014-05-07.
  10. ^"Enumerable.Count". Retrieved2014-05-07.
  11. ^".NET Language-Integrated Query for XML Data". 30 April 2007. Retrieved2007-11-30.
  12. ^"LINQ to SQL". Archived fromthe original on 2013-01-25. Retrieved2007-11-30.
  13. ^abc"LINQ to SQL: .NET Language-Integrated Query for Relational Data". 30 April 2007. Retrieved2007-11-30.
  14. ^"LINQ to DataSets". Archived fromthe original on 2013-01-25. Retrieved2007-11-30.
  15. ^Vider, Guy (2007-12-21)."LINQ Performance Test: My First Visual Studio 2008 Project". Retrieved2009-02-08.
  16. ^Parsons, Jared (2008)."Increase LINQ Query Performance".Microsoft Developer Network. Retrieved2014-03-19.While it is true that LINQ is powerful and very efficient, large sets of data can still cause unexpected performance problems
  17. ^Alva, Jaime (2010-08-06)."Potential Performance Issues with Compiled LINQ Query Re-Compiles".Microsoft Developer Network. Retrieved2014-03-19.When calling a query multiple times with Entity Framework the recommended approach is to use compiled LINQ queries. Compiling a query results in a performance hit the first time you use the query but subsequent calls execute much faster
  18. ^Kshitij, Pandey (2008-05-25)."Performance comparisons LinQ to SQL, ADO, C#". Retrieved2009-02-08.
  19. ^"ParallelEnumerable Class". Retrieved2014-05-07.
  20. ^"Programming in the Age of Concurrency: Concurrent Programming with PFX". Retrieved2007-10-16.
  21. ^Eichert, Steve; Wooley, James B.; Marguerie, Fabrice (2008).LINQ in Action. Manning. pp. 56–57 (as reported in the Google Books search link - the book does not have page numbers).ISBN 9781638354628.
  22. ^Concepts behind the C# 3.0 language | Articles | TomasP.NetArchived 2007-02-12 at theWayback Machine
  23. ^"The Joins Concurrency Library". Retrieved2007-06-08.

External links

[edit]
Wikibooks has a book on the topic of:.NET Development Foundation
Implementations
Architecture
Components
Tools
Decompilers
Obfuscators
IDEs
Organizations
In current use
Proprietary
Superseded
Retrieved from "https://en.wikipedia.org/w/index.php?title=Language_Integrated_Query&oldid=1319367491#Predecessor_languages"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp