Skip navigation.

Giáng sinh an lành - Năm mới đầm ấm và hạnh phúc

Posts tagged with "Standard Query Operators"

Aggregate operators in LINQ

,


1. Count
The Count operator counts the number of elements in a sequence.
public static int Count<T>(
this IEnumerable<T> source);
public static int Count<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The Count operator without a predicate first checks whether the source sequence implements ICollection<T>. If so, the sequence’s implementation of ICollection<T> is used to obtain the element count. Otherwise, the source sequence is enumerated to count the number of elements.
The Count operator with a predicate enumerates the source sequence and counts the number of elements for which the predicate function returns true.
For both Count operators, an ArgumentNullException is thrown if any argument is null, and an OverflowException is thrown if the count exceeds int.MaxValue.
The following example returns the number of customers in London:
int count = customers.Count(c => c.City == "London");


2. LongCount
The LongCount operator counts the number of elements in a sequence.
public static long LongCount<T>(
this IEnumerable<T> source);
public static long LongCount<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The LongCount operator enumerates the source sequence and counts the number of elements for which the predicate function returns true. If no predicate function is specified the LongCount operator simply counts all elements. The count of elements is returned as a value of type long.
For both Count operators, an ArgumentNullException is thrown if any argument is null.

3. Sum
The Sum operator computes the sum of a sequence of numeric values.
public static Numeric Sum(
this IEnumerable<Numeric> source);
public static Numeric Sum<T>(
this IEnumerable<T> source,
Func<T, Numeric> selector);

The Numeric type is one of int, int?, long, long?, double, double?, decimal, and decimal?.
The Sum operator enumerates the source sequence, invokes the selector function for each element, and computes the sum of the resulting values. If no selector function is specified, the sum of the elements themselves is computed. An ArgumentNullException is thrown if any argument is null. If the sum is too large to represent using the Numeric type, an OverflowException is thrown or, for double and double?, a positive or negative infinity is returned.
The Sum operator returns zero for an empty sequence. Furthermore, the operator does not include null values in the result (null values can occur when the Numeric type is a nullable type).
The following example produces a sequence of customer names and order totals for a given year:
int year = 2005;
var namesAndTotals =
customers.
Select(c => new {
c.Name,
TotalOrders =
c.Orders.
Where(o => o.OrderDate.Year == year).
Sum(o => o.Total)
});

Read more...

Quantifiers in LINQ

,


1. Any
The Any operator checks whether any element of a sequence satisfies a condition.
public static bool Any<T>(
this IEnumerable<T> source);
public static bool Any<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The Any operator enumerates the source sequence and returns true if any element satisfies the test given by the predicate. If no predicate function is specified the Any operator simply returns true if the source sequence contains any elements.
The enumeration of the source sequence is terminated as soon as the result is known.
An ArgumentNullException is thrown if any argument is null.
The following example checks whether any products with a price of 100 or more are out of stock.
bool b = products.Any(p => p.UnitPrice >= 100 && p.UnitsInStock == 0);


2. All
The All operator checks whether all elements of a sequence satisfy a condition.
public static bool All<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The All operator enumerates the source sequence and returns true if no element fails the test given by the predicate.
The enumeration of the source sequence is terminated as soon as the result is known.
An ArgumentNullException is thrown if any argument is null.
The All operator returns true for an empty sequence. This is consistent with established predicate logic and other query languages such as SQL.
The following example produces the names of the product categories for which all products are in stock:
IEnumerable<string> fullyStockedCategories =
products.
GroupBy(p => p.Category).
Where(g => g.Group.All(p => p.UnitsInStock > 0)).
Select(g => g.Key);


3. Contains
The Contains operator checks whether a sequence contains a given element.
public static bool Contains<T>(
this IEnumerable<T> source,
T value);

The Contains operator first checks whether the source sequence implements ICollection<T>. If so, the Contains method in sequence’s implementation of ICollection<T> is invoked to obtain the result. Otherwise, the source sequence is enumerated to determine if it contains an element with the given value. If a matching element is found, the enumeration of the source sequence is terminated at that point. The elements and the given value are compared using the default equality comparer, EqualityComparer<K>.Default.
An ArgumentNullException is thrown if the source argument is null.

Generation operators in LINQ

,

1. Range
The Range operator generates a sequence of integral numbers.
public static IEnumerable<int> Range(
int start,
int count);

The Range operator allocates and returns an enumerable object that captures the arguments. An ArgumentOutOfRangeException is thrown if count is less than zero or if start + count – 1 is larger than int.MaxValue. When the object returned by Range is enumerated, it yields count sequential integers starting with the value start.
The following example produces an array of the squares of the numbers from 0 to 99:
int[] squares = Sequence.Range(0, 100).Select(x => x * x).ToArray();


2. Repeat
The Repeat operator generates a sequence by repeating a value a given number of times.
public static IEnumerable<T> Repeat<T>(
T element,
int count);

The Repeat operator allocates and returns an enumerable object that captures the arguments. An ArgumentOutOfRangeException is thrown if the specified count is less than zero. When the object returned by Repeat is enumerated, it yields count occurrences of element.
The following example produces a long[] with 256 elements containing the value -1.
long[] x = Sequence.Repeat(-1L, 256).ToArray();


3. Empty
The Empty operator returns an empty sequence of a given type.
public static IEnumerable<T> Empty<T>();

The Empty operator caches a single empty sequence of the given type. When the object returned by Empty is enumerated, it yields nothing.
The following obtains an empty sequence of customers:
IEnumerable<Customer> noCustomers = Sequence.Empty<Customer>();

Element operators in LINQ

,

1. First
The First operator returns the first element of a sequence.
public static T First<T>(
this IEnumerable<T> source);
public static T First<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The First operator enumerates the source sequence and returns the first element for which the predicate function returns true. If no predicate function is specified, the First operator simply returns the first element of the sequence.
An ArgumentNullException is thrown if any argument is null. An InvalidOperationException is thrown if no element matches the predicate or if the source sequence is empty.
The following example returns the first customer with a given phone number:
string phone = "206-555-1212";
Customer c = customers.First(c => c.Phone == phone);

In the example above, an exception is thrown if no customer with the given phone number exists. To instead return null when no element is found, use the FirstOrDefault operator.

2. FirstOrDefault
The FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found.
public static T FirstOrDefault<T>(
this IEnumerable<T> source);
public static T FirstOrDefault<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The FirstOrDefault operator enumerates the source sequence and returns the first element for which the predicate function returns true. If no predicate function is specified, the FirstOrDefault operator simply returns the first element of the sequence.
An ArgumentNullException is thrown if any argument is null. If no element matches the predicate or if the source sequence is empty, default(T) is returned. The default value for reference and nullable types is null.
3. Last
The Last operator returns the last element of a sequence.
public static T Last<T>(
this IEnumerable<T> source);
public static T Last<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The Last operator enumerates the source sequence and returns the last element for which the predicate function returned true. If no predicate function is specified, the Last operator simply returns the last element of the sequence.
An ArgumentNullException is thrown if any argument is null. An InvalidOperationException is thrown if no element matches the predicate or if the source sequence is empty.

4. LastOrDefault
The LastOrDefault operator returns the last element of a sequence, or a default value if no element is found.
public static T LastOrDefault<T>(
this IEnumerable<T> source);
public static T LastOrDefault<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

The LastOrDefault operator enumerates the source sequence and returns the last element for which the predicate function returned true. If no predicate function is specified, the LastOrDefault operator simply returns the last element of the sequence.
An ArgumentNullException is thrown if any argument is null. If no element matches the predicate or if the source sequence is empty, default(T) is returned. The default value for reference and nullable types is null.

Read more...

Equality operator in LINQ

,

EqualAll
The EqualAll operator checks whether two sequences are equal.
public static bool EqualAll<T>(
this IEnumerable<T> first,
IEnumerable<T> second);

The EqualAll operator enumerates the two source sequences in parallel and compares corresponding elements using the Equals static method in System.Object. The method returns true if all corresponding elements compare equal and the two sequences are of equal length. Otherwise, the method returns false. An ArgumentNullException is thrown if either argument is null.

Conversion operators in LINQ

,

1. ToSequence
The ToSequence operator returns its argument typed as IEnumerable<T>.
public static IEnumerable<T> ToSequence<T>(
this IEnumerable<T> source);

The ToSequence operator simply returns the source argument. The operator has no effect other than to change the compile-time type of the source argument to IEnumerable<T>.
The ToSequence operator can be used to choose between query operator implementations in cases where a collection implements IEnumerable<T> but also has a different set of public query operators. For example, given a class Table<T> that implements IEnumerable<T> as well as its own Where, Select, SelectMany, and so on, the query
Table<Customer> custTable = GetCustomersTable();
var query = custTable.Where(c => IsGoodCustomer(c));

will invoke the public Where operator of Table<T>. A Table<T> type that represents a database table would likely have a Where operator that takes the predicate argument as an expression tree and converts the tree into SQL for remote execution. If remote execution is not desired, for example because the predicate invokes a local method, the ToSequence operator can be used to hide Table<T>’s operators and instead make the Standard Query Operators available:
Table<Customer> custTable = GetCustomersTable();
var query = custTable.ToSequence().Where(c => IsGoodCustomer(c));

This would now cause the query to execute locally.

2. ToArray
The ToArray operator creates an array from a sequence.
public static T[] ToArray<T>(
this IEnumerable<T> source);

The ToArray operator enumerates the source sequence and returns an array containing the elements of the sequence. An ArgumentNullException is thrown if the source argument is null.
The following example produces an array of the names of all countries in which there are customers:
string[] customerCountries =
customers.Select(c => c.Country).Distinct().ToArray();


3. ToList
The ToList operator creates a List<T> from a sequence.
public static List<T> ToList<T>(
this IEnumerable<T> source);

The ToList operator enumerates the source sequence and returns a List<T> containing the elements of the sequence. An ArgumentNullException is thrown if the source argument is null.
The following example produces a List<Customer> containing those customers that placed orders in 2005:
List<Customer> customersWithOrdersIn2005 =
customers.
Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
ToList();

4. ToDictionary
The ToDictionary operator creates a Dictionary<K,E> from a sequence.
public static Dictionary<K, T> ToDictionary<T, K>(
this IEnumerable<T> source,
Func<T, K> keySelector);
public static Dictionary<K, T> ToDictionary<T, K>(
this IEnumerable<T> source,
Func<T, K> keySelector,
IEqualityComparer<K> comparer);
public static Dictionary<K, E> ToDictionary<T, K, E>(
this IEnumerable<T> source,
Func<T, K> keySelector,
Func<T, E> elementSelector);
public static Dictionary<K, E> ToDictionary<T, K, E>(
this IEnumerable<T> source,
Func<T, K> keySelector,
Func<T, E> elementSelector,
IEqualityComparer<K> comparer);

The ToDictionary operator enumerates the source sequence and evaluates the keySelector and elementSelector functions for each element to produce that element’s key and value. The resulting key and value pairs are returned in a Dictionary<K,E>. If no elementSelector was specified, the value for each element is simply the element itself. An ArgumentNullException is thrown if the source, keySelector, or elementSelector argument is null or if a key value produced by keySelector is null. An ArgumentException is thrown if keySelector produces a duplicate key value for two elements. In the resulting dictionary, key values are compared using the given comparer, or, if a null comparer was specified, using the default equality comparer, EqualityComparer<K>.Default.
The following example creates a Dictionary<int,Order> that maps from order ID to order for all orders in 2005:
Dictionary<int,Order> orders =
customers.
SelectMany(c => c.Orders).
Where(o => o.OrderDate.Year == 2005).
ToDictionary(o => o.OrderID);

The following example creates a Dictionary<string,decimal> that maps from category name to the maximum product price in that category:
Dictionary<string,decimal> categoryMaxPrice =
products.
GroupBy(p => p.Category).
ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));

Read more...