LINQ / C#

LINQ Query Operators

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 CategoryLINQ Query Operators Names
FilteringWhere, OfType
SortingOrderBy, OrderByDescending, ThenBy, ThenByDescending
SetExcept, Intersect, Union, Distinct
QuantifierAll, Any, Contains
ProjectionSelect, SelectMany
PartitioningSkip, SkipWhile, Take, TakeWhile
JoinJoin, GroupJoin
GroupingGroupBy, ToLookup
SequencingDefaultIfEmpty, Empty, Range, Repeat
EqualitySequenceEqual
ElementElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault
ConversionAsEnumerable, AsQueryable, Cast, OfType, ToArray, ToDictionary, ToList, ToLookup
ConcatenationConcat
AggregationAggregate, 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 OperatorsDescription
WhereFilter elements based on the condition.
OfTypeThis 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 OperatorsDescription
OrderBySort elements in ascending order
OrderByDescendingSort elements in descending order
ThenByAgain 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.
ThenByDescendingAgain 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 OperatorsDescription
DistinctRemoves duplicates elements from single sequence
ExceptReturns elements which are not present in second sequence
IntersectReturns common elements between two sequences
UnionReturns 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 OperatorsDescription
AllReturns true when all elements in a sequence satisfy a condition else returns false.
AnyReturns true when any single element in a sequence satisfy a condition else returns false
ContainsReturns 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 OperatorsDescription
SelectTransform each element by using lambda expression. For example, students.Select(w => w.Name)
SelectManyWe 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 OperatorsDescription
TakeReturns only those elements upto specify index. For example, returns only first first elements in a sequence.
TakeWhileReturns 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.
SkipReturns only those elements after specify index. For example, skip first five elements and returns all rest elements.
SkipWhileSkip 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 OperatorsDescription
JoinJoins two sequences based on matching keys.
GroupJoinJoins 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 OperatorsDescription
GroupByGroup elements based on specific key.
ToLookupGroup elements and returns as (Key, Value) pair objects.

Sequencing Operators

These LINQ query operators are used to create a new sequence of values.

Sequencing OperatorsDescription
DefaultIfEmptyReturns a default blank sequence. Mainly used for adding default element if source collection is empty.
EmptyReturns an empty sequence.
RangeReturns a range a numeric numbers. For example, we need a new sequence starting from 1 to 10.
RepeatReturns 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 OperatorsDescription
SequenceEqualCompares 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 OperatorsDescription
ElementAtReturns an element at specific index in a sequence. Throws ArgumentOutOfRangeException exception when index is outside length of sequence.
ElementAtOrDefaultReturns an element at specific index in a sequence. If element not found returns a blank value.
FirstReturns first element in a sequence or first element that satisfy a condition. Throws InvalidOperationException exception when sequence is empty.
FirstOrDefaultReturns 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.
LastReturns last element in a sequence or last element that satisfy a condition. Throws InvalidOperationException exception when sequence is empty.
LastOrDefaultReturns 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.
SingleReturns single element in a sequence or element that satisfy a condition. If a sequence has more than one elements then throws InvalidOperationException exception.
SingleOrDefaultReturns 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 OperatorsDescription
AsEnumerableReturns a new sequence of IEnumerable<T>.
AsQueryableReturns a new sequnce of IQueryable<T>.
CastCast the element to a specific type.
OfTypeThis 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>.
ToArrayReturns a new sequence of an array[] data type
ToDictionaryReturns a new sequence of generic Dictionary<Key,Value> type.
ToListReturn a new sequence of generic List type.
ToLookupGroup 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 OperatorsDescription
ConcatConcatenate 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 OperatorsDescription
AverageComputer average values of all elements in a sequence.
CountCounts the number of elements in a sequence.
LongCountCount the number of elements in a huge sequence. Use LongCount where a sequence has more than int.MaxValue elements. Returns a long data type.
MaxReturns the maximum value in a sequence.
MinReturns the minimum value in a sequence.
SumReturns the sum of all elements in a sequence.
AggregateUse for performing custom aggregation operation on a sequence.