LINQ

suggest change

Versions

LINQ to Objects shipped in .NET Framework 3.5 and .NET Compact Framework 3.5, and remains in .NET Framework through 4.6.2 (Compact Framework also 3.7 and 3.9).

Introduction

LINQ (Language Integrated Query) is a set of language and library features for querying data. It offers one model for working with different sources and formats. In a LINQ query you work with objects. The same patterns query and transform XML documents, SQL databases, ADO.NET DataSets, .NET collections, and anything else that has a provider. LINQ can be used from C# and Visual Basic.

Syntax

Remarks

The LINQ built-in methods are extension methods for the IEnumerable<T> interface that live in the System.Linq.Enumerable class in the System.Core assembly. They are available in .NET Framework 3.5 and later.

LINQ allows for simple modification, transformation, and combination of various IEnumerables using a query-like or functional syntax.

While the standard LINQ methods can work on any IEnumerable<T>, including the simple arrays and List<T>s, they can also be used on database objects, where the set of LINQ expressions can be transformed in many cases to SQL if the data object supports it. See LINQ to SQL.

For methods that compare elements (such as Contains and Except), IEquatable<T>.Equals is used when T implements that interface. Otherwise the type's Equals and GetHashCode are used (they may override Object). Overloads of these methods also accept an IEqualityComparer<T>. Default equality for string is ordinal, not culture-sensitive.

For the ...OrDefault methods, default(T) is used to generate default values.

Official reference: Enumerable class

Lazy Evaluation

Virtually every query that returns an IEnumerable<T> is not evaluated immediately; instead, the logic is delayed until the query is iterated over. One implication is that each time someone iterates over an IEnumerable<T> created from one of these queries, e.g., .Where(), the full query logic is repeated. If the predicate is long-running, this can be a cause for performance issues.

One simple solution (when you know or can control the approximate size of the resulting sequence) is to fully buffer the results using .ToArray() or .ToList(). .ToDictionary() or .ToLookup() can fulfill the same role. One can also, of course, iterate over the entire sequence and buffer the elements according to other custom logic.

ToArray() or ToList()?

Both .ToArray() and .ToList() loop through all elements of an IEnumerable<T> sequence and save the results in a collection stored in-memory. Use the following guidelines to determine which to choose:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents