LINQ Operators

Operators are the essential ingredients of a LINQ query expression. Several operators, such as Where, Join, and Select, already have been featured in previous samples. The operators accept IEnumerable<T> and IQueryable<T> interfaces as input. The IEnumerable<T> interface supports iteration. IQueryable<T> is implemented by a LINQ provider to evaluate query expressions in that context. For example, the LINQ to XML provider implements the IQuerable<T> interface to provide XML-specific behavior. IQueryable<T> inherits the IEnumerable<T> interface. For that reason, IQueryable<T> objects are also enumerable.

There are several operators, which are grouped into categories. In this section, all the operators in LINQ are presented. The operators are available as extension methods and accept a collection as the this parameter. The core extension methods for LINQ are found in the Enumerable<T> class of the System.Linq namespace.

C# language syntax for query expressions supports relatively few LINQ operators. The expressions that are supported by C# syntax are documented in the following sections.

Aggregation Operators

Aggregation operators calculate a scalar value from a collection. Table 6-2 lists the aggregation operators.

Table 6-2. Aggregation operators

Extension method

C# syntax

Description

Aggregate

N/A

Performs aggregation using a custom accumulator function. The function is called for each element.

The following extension method example is equivalent to the Sum operator, which is a predefined aggregation operator.

collection.Aggregate((accumulator,value) => accumulator += value);

Average

N/A

Calculates the average of a collection.

Example of extension method:

collection.Average();

Count

N/A

Count of elements in a collection.

Example of extension method:

collection.Count();

LongCount

N/A

Count of elements in a large collection. Returns an Int64 value.

Example of extension method:

collection.LongCount();

Max

N/A

Maximum value in a collection.

Example of extension method:

collection.Max();

Min

N/A

Minimum value in a collection.

Example of extension method:

collection.Min();

Sum

N/A

Sum values in a collection.

Example of extension method:

collection.Sum();

Concatenation Operator

Concatenation operator concatenates two sequences into one sequence.

The sole concatenation operator is the Concat operator, which concatenates two collections or sequences.

Here is an example of the extension method:

collection1.Concat(collection2);

Data Type Conversion Operators

Data type conversion operators convert the source collection into another type. Some of these operators are not deferred, and the query expression immediately returns the results of the operator.

Table 6-3 lists the data type conversion operators.

Table 6-3. Data type conversion operators

Extension Method

C# Syntax

Description

AsEnumerable

N/A

For queryable objects, returns the separate IEnumerable<T> interface implementation, if any.

Example of extension method:

collection.AsEnumerable();

AsQueryable

N/A

For enumerable objects, returns the separate IQueryable<T> interface implementation, if any.

Example of extension method:

collection.AsEnumerable();

Cast

From typevariable in nongeneric select variable

Converts a non-generic enumerable collection into a generic enumerable collection of the specified type.

Example of extension method:

nongeneric.Cast<Type>();

Example of C# language syntax:

from Type i in nongeneric select i;

OfType

N/A

Returns only elements related to the specified type from the collection.

Example of extension method:

collection.OfType<Type>();

ToArray

N/A

Converts a collection to an array. The query expression is immediately evaluated.

Example of extension method:

collection.ToArray<int>()

ToDictionary

N/A

Converts a collection into a dictionary. In the following example, collection is an array of objects that have a field called key. The key field is a unique value. The query expression is immediately evaluated.

Example of extension method:

collection.ToDictionary(d => d.key);

ToList

N/A

Converts a collection to a list. The query expression is immediately evaluated.

Example of extension method:

collection.ToList();

ToLookup

N/A

Converts a collection to a lookup table. The query expression is immediately evaluated.

Example of extension method:

collection.ToLookup(d => d.key);

Element Operators

Element operators return a specific element of a collection. The elements of the collection comprise a zero-based list.

Table 6-4 lists the element operators.

Table 6-4. Element operators

Extension method

C# syntax

Description

ElementAt

N/A

Returns an element at a specific index.

Example of extension method:

collection.ElementAt(1);

ElementAtOrDefault

N/A

Returns an element at a specific index. If out of bounds, a default value (zero or null) is returned.

Example of extension method:

collection.ElementAtOrDefault(20);

First

N/A

Returns the first element of a collection.

Example of extension method:

collection.First();

FirstOrDefault

N/A

Returns the first element of a collection. If out of bounds, a default value (zero or null) is returned.

Example of extension method:

collection.FirstOrDefault();

Last

N/A

Returns the last element of a collection.

Example of extension method:

collection.Last();

LastOrDefault

N/A

Returns the last element of a collection. If out of bounds, a default value (zero or null) is returned.

Example of extension method:

collection.LastOrDefault();

Single

N/A

Confirms that a collection has a single element. An exception occurs if the collection does not have exactly one element. Otherwise, it returns that element.

Example of extension method:

collection.Single();

SingleOrDefault

N/A

Confirms that a collection has a single element. Returns a default value if the collection does not have exactly one element. Otherwise, it returns the single element of the collection.

Example of extension method:

collection.SingleOrDefault();

Equality Operator

Equality operator compares two sequences. If the sequences have the same number of elements and the values are equal, the sequences are equal.

The sole equality operator is the SequenceEqual operator, which compares two sequences and returns true if the sequences are equal. Otherwise, the operator returns false.

Here is an example of the extension method:

collection1.SequenceEqual(collection2);

Filtering Operator

Filtering operator filters a collection based on a function. The function is called on each element of the collection and returns a Boolean expression. If true, the element is included; otherwise, it is omitted.

The sole filtering operator is the Where operator, which returns a collection. The elements of the collection are chosen by evaluating for each element a function that returns a Boolean expression.

Here is an example of the extension method:

collection.Where(info => info > 3);

And here is an example of C# language syntax:

from info in data where info > 3 select info;

Generation Operators

Generation operators create a collection that contains a sequence of values.

Table 6-5 lists the generation operators.

Table 6-5. Generation operators

Extension method

C# syntax

Description

DefaultIfEmpty

N/A

Creates a singleton collection if the collection is empty. Otherwise, returns the collection.

Example of extension method:

collection.DefaultIfEmpty();

Empty

N/A

Creates an empty collection. This is a static method.

Example of extension method:

Enumerable.Empty<Type>();

Range

N/A

Creates a collection that contains a sequence of integers. This is a static method. The following Range operator will create a collection containing a sequence from 5 to 10, inclusive.

Example of extension method:

Enumerable.Range(5,10);

Repeat

N/A

Creates a collection that repeats a single value. This is a static method. The following example creates a collection with five elements. Each element has the value 2.

Example of extension method:

Enumerable.Repeat(2,5);

Grouping Operator

Grouping operator allows the grouping of elements by a field attribute.

The sole grouping operator is the GroupBy operator, which groups elements that share a common value.

Here is an example of the extension method:

collection.GroupBy(c => c.key);.

Join Operators

Join operators join two data sources based on a common field attribute. This allows the correlation of two data sources.

Table 6-6 lists the join operators.

Table 6-6. Join operators

Extension method

C# syntax

Description

GroupJoin

from outer join inner equals Boolean into GroupCollection select resulttype

Joins two data sources and groups the inner collection. If, for example, there are two lists (a list of car owners and a list of cars), a group join could return a collection of anonymous types. Each item in the collection would represent a car owner and the list of cars owned by that person.

Example of extension method:

oCollection.GroupJoin(iData, outer => outer.key,
    inner => inner.key, (outer, innerData) => new {
    outer = outer,items = innerCollection.Select(inner.
key) });

Example of C# language syntax:

from outer in oData join inner in iData
    on outer equals inner.key into iGroup
    select new { outer, items = iGroup };

Join

from outer join inner equals Boolean select result

Joins two data sources based on a common field.

Example of extension method:

oCollection.Join(iData, outer => outer.key, inner =>
inner.key,
     (outer, inner) => new { inner.name, outer.key });

Example of C# language syntax:

from outer in oData join inner in iData
    on outer.key equals inner.key
    select new { inner.name, outer.key };

Partitioning Operators

Partitioning operators partition a collection and return the result.

Table 6-7 lists the partitioning operators.

Table 6-7. Partitioning operators

Extension method

C# syntax

Description

Skip

N/A

Skips the specified number of elements in a sequence.

Example of extension method:

collection.Skip(3);

SkipWhile

N/A

Skips while a condition is met.

Example of extension method:

collection.SkipWhile(d => d < 45);

Take

N/A

Takes elements up to the specified position.

Example of extension method:

collection.Take(3);

TakeWhile

N/A

Takes elements while a condition is met.

Example of extension method:

collection.TakeWhile(d => d < 30);

Quantifier Operators

Quantifier operators return a Boolean expression indicating whether all elements of a collection satisfy a particular condition.

Table 6-8 lists the quantifier operators.

Table 6-8. Quantifier operators

Extension method

C# syntax

Description

All

N/A

Returns true if all elements of a collection meet the specified condition.

Example of extension method:

collection.All(d => d > 30);

Any

N/A

Returns true if any element of a collection meets the specified condition.

Example of extension method:

collection.Any(d => d > 30);

Contains

N/A

Returns true if the collection contains the specified element.

Example of extension method:

collection.Contains(45);

Set Operators

Set operators extract a set of elements from the source collection and return the results in a new collection.

Table 6-9 lists the set operators.

Table 6-9. Set operators

Extension method

C# syntax

Description

Distinct

N/A

Deletes duplicate elements from a collection.

Example of extension method:

collection.Distinct()

Except

N/A

Compares two collections and returns the elements that appear in only one of the collections.

Example of extension method:

collection1.Except(collection2);

Intersect

N/A

Compares two collections and returns only those elements that appear in both.

Example of extension method:

collection1.Intersect(collection2);

Union

N/A

Combines two collections, while removing duplicates.

Example of extension method:

collection1.Union(collection2);

Sorting Operators

Sorting operators modify the sequence of elements in a collection.

Table 6-10 lists the sorting operators.

Table 6-10. Sorting operators

Extension method

C# syntax

Description

OrderBy

from type in collection orderby

key select result

Sorts a collection in ascending order using a key.

Example of extension method:

collection.OrderBy(item => item.key);

Example of C# language syntax:

from item in data orderby item.key select
item;

OrderByDescending

from type in collection orderby

key

descending select result

Sorts a collection in ascending order using a key.

Example of extension method:

collection.OrderByDescending(item => item.
key);

Example of C# language syntax:

from item in data orderby item.key descending
select item;

Reverse

N/A

Reverses the elements in a collection.

Example of extension method:

collection.Reverse();

ThenBy

from type in collection orderby

key1, key2, ... keyn select result

Sorts a collection with a series of nested collections.

Example of extension method:

collection.OrderBy(item => item.key).ThenBy(item
=> item);

Example of C# language syntax:

from item in data orderby item.key, item
select item;

ThenByDescending

from type in collection orderby

key1, key2, ... keyn descending select result

Orders a collection first by the Order statement and then by the ThenByDescending statement.

Example of extension method:

collection.OrderBy(item => item.key).
    ThenByDescending(item => item);

Example of C# language Syntax:

from item in data orderby item.key, item
descending
    select item;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.42.116