LINQ provides more than 50 query operators for different functionalities. Every query operator is an extension method.
These operators can be categorized into following one:
Operator Category | LINQ Query Operators Names |
---|---|
Filtering | Where, OfType |
Sorting | OrderBy, OrderByDescending, ThenBy, ThenByDescending |
Set | Except, Intersect, Union, Distinct |
Quantifier | All, Any, Contains |
Projection | Select, SelectMany |
Partitioning | Skip, SkipWhile, Take, TakeWhile |
Join | Join, GroupJoin |
Grouping | GroupBy, ToLookup |
Sequencing | DefaultIfEmpty, Empty, Range, Repeat |
Equality | SequenceEqual |
Element | ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault |
Conversion | AsEnumerable, AsQueryable, Cast, OfType, ToArray, ToDictionary, ToList, ToLookup |
Concatenation | Concat |
Aggregation | Aggregate, Average, Count, LongCount, Max, Min, Sum |
Below is basic explanation of each LINQ operator. I shall cover all operator with examples in next blogs.
Filtering Operators
Filter operators are used to select only those elements from sequence that satisfy a condition. For example, suppose we have ten names in a collection sequence and we have to filter out those names that start with “K”.
Filtering Operators | Description |
---|---|
Where | Filter elements based on the condition. |
OfType | This operator takes a Type name and select only those elements in the collection that have matching type.For example, we have a collection of base class (List<BaseClass>) and we have added some items of derived class in the collection. Now we have to find out those item that have of type derived type OfType<DerivedClass>. |
Sorting Operators
These operators are used to order the elements in a sequence either ascending or in descending order. We can apply sort elements multiple fields.
Sorting Operators | Description |
---|---|
OrderBy | Sort elements in ascending order |
OrderByDescending | Sort elements in descending order |
ThenBy | Again sort elements in ascending order. Must use after OrderBy or OrderByDescending operator. This operator is useful when we have to apply sorting based on multiple fields. For example, we want to sort first based on name and then age. |
ThenByDescending | Again sort elements in descending order. Must use after OrderBy or OrderByDescending operator. This operator is useful when we have to apply sorting based on multiple fields. For example, we want to sort descending first based on age and then name. |
Set Operators
These LINQ query operators are used to find common elements, unique elements, missing elements between two collection sequences.
Set Operators | Description |
---|---|
Distinct | Removes duplicates elements from single sequence |
Except | Returns elements which are not present in second sequence |
Intersect | Returns common elements between two sequences |
Union | Returns unique elements between two sequence |
Quantifier Operators
These LINQ query operators are used in conditional statements like if and switch to test whether any or all elements in a sequence satisfy a condition.
Quantifier Operators | Description |
---|---|
All | Returns true when all elements in a sequence satisfy a condition else returns false. |
Any | Returns true when any single element in a sequence satisfy a condition else returns false |
Contains | Returns true when a sequence contains a matching element else returns false. |
Projection Operators
These LINQ query operators are used in create a new type by choosing only those objects or properties that we need in our result set. Projection operators provides cross joins and non equi joins like functionality.
For example, suppose we use two objects in a LINQ query and in the result set we only need two properties of first object and one property of second object so we create a new object by using projection operator that has three properties and return that object from query.
Projection Operators | Description |
---|---|
Select | Transform each element by using lambda expression. For example, students.Select(w => w.Name) |
SelectMany | We use this operator when each element is a collection and SelectMany transform each collection in a single collection and returns as a result set. For example, we have two elements {“First”, “Second”} and {“Third”,”Fourth”} and SelectMany returns {“First”, “Second”, “Third”, “Fourth”} |
Partitioning Operators
These LINQ query operators are used to filter out elements based on the indexes or by a condition in a sequence. These operators are also used for implementing paging.
Partitioning Operators | Description |
---|---|
Take | Returns only those elements upto specify index. For example, returns only first first elements in a sequence. |
TakeWhile | Returns first matching elements which satisfies a given condition.For example, we have numbers { 1, 2, 9, 10, 3, 4} in a sequence and we want to filter out elements which are smaller than 5 then TakeWhile returns only { 1, 2} in a result set as they are appearing first in a list and 9 element dissatisfy this condition. |
Skip | Returns only those elements after specify index. For example, skip first five elements and returns all rest elements. |
SkipWhile | Skip those elements that satisfies a given condition |
Join Operators
These LINQ query operators are used to combine multiple sequence into one sequence just like joins in SQL queries. Join operators offers inner join and left outer joins like functionality.
Join Operators | Description |
---|---|
Join | Joins two sequences based on matching keys. |
GroupJoin | Joins two sequence based on matching keys but returns hierarchical output. |
Grouping Operators
These LINQ query operators are used to group the data based on specific keys just like groups in SQL.
Grouping Operators | Description |
---|---|
GroupBy | Group elements based on specific key. |
ToLookup | Group elements and returns as (Key, Value) pair objects. |
Sequencing Operators
These LINQ query operators are used to create a new sequence of values.
Sequencing Operators | Description |
---|---|
DefaultIfEmpty | Returns a default blank sequence. Mainly used for adding default element if source collection is empty. |
Empty | Returns an empty sequence. |
Range | Returns a range a numeric numbers. For example, we need a new sequence starting from 1 to 10. |
Repeat | Returns a sequence of repeating same value at specific number of times. For example, we need five elements of value “Default” in a collection. |
Equality Operators
There is only one operator in this category. This operator is used to compare sequences.
Equality Operators | Description |
---|---|
SequenceEqual | Compares two sequences and returns true if they are exact match. Also takes a second parameter of IEqualityComparer<T> if we want to use different comparer. |
Element Operators
These LINQ query operators are used to find element at specific index in a sequence.
Element Operators | Description |
---|---|
ElementAt | Returns an element at specific index in a sequence. Throws ArgumentOutOfRangeException exception when index is outside length of sequence. |
ElementAtOrDefault | Returns an element at specific index in a sequence. If element not found returns a blank value. |
First | Returns first element in a sequence or first element that satisfy a condition. Throws InvalidOperationException exception when sequence is empty. |
FirstOrDefault | Returns first element in a sequence or first element that satisfy a condition. If sequence is empty or no element matches the condition then returns default value. |
Last | Returns last element in a sequence or last element that satisfy a condition. Throws InvalidOperationException exception when sequence is empty. |
LastOrDefault | Returns last element in a sequence or last element that satisfy a condition. If sequence is empty or no element matches the condition then returns default value. |
Single | Returns single element in a sequence or element that satisfy a condition. If a sequence has more than one elements then throws InvalidOperationException exception. |
SingleOrDefault | Returns single element in a sequence or element that satisfy a condition. If sequence is empty or no element matches the condition then returns default value. |
Conversion Operators
These LINQ query operators are used to convert element of sequence to another data types.
Conversion Operators | Description |
---|---|
AsEnumerable | Returns a new sequence of IEnumerable<T>. |
AsQueryable | Returns a new sequnce of IQueryable<T>. |
Cast | Cast the element to a specific type. |
OfType | This operator takes a Type name and select only those elements in the collection that have matching type.For example, we have a collection of base class (List<BaseClass>) and we have added some items of derived class in the collection. Now we have to find out those item that have of type derived type OfType<DerivedClass>. |
ToArray | Returns a new sequence of an array[] data type |
ToDictionary | Returns a new sequence of generic Dictionary<Key,Value> type. |
ToList | Return a new sequence of generic List type. |
ToLookup | Group elements and returns as (Key, Value) pair objects. |
Concatenation Operators
There is only one operator in this category. Used to create new collection based on two sequences.
Concatenation Operators | Description |
---|---|
Concat | Concatenate two sequences and create one new sequence joining all the elements of both sequences. |
Aggregation Operators
These LINQ query operators are used to compute mathematical functions like sum, average, count, max and min operators on elements.
Aggregation Operators | Description |
---|---|
Average | Computer average values of all elements in a sequence. |
Count | Counts the number of elements in a sequence. |
LongCount | Count the number of elements in a huge sequence. Use LongCount where a sequence has more than int.MaxValue elements. Returns a long data type. |
Max | Returns the maximum value in a sequence. |
Min | Returns the minimum value in a sequence. |
Sum | Returns the sum of all elements in a sequence. |
Aggregate | Use for performing custom aggregation operation on a sequence. |