The .

NET Standard Query Operators
May 2006

Copyright © Microsoft Corporation 2006. All Rights Reserved.

Notice © 2006 Microsoft Corporation. All rights reserved. Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries/regions. Other product and company names mentioned herein may be the trademarks of their respective owners.

Copyright © Microsoft Corporation 2006. All Rights Reserved.

Table of Contents

Table of Contents
1. Technical Specification...................................................................................................................................1 1.1 The Func delegate types..............................................................................................................................2 1.2 The Sequence class......................................................................................................................................2 1.3 Restriction operators....................................................................................................................................2 1.3.1 Where...................................................................................................................................................2 1.4 Projection operators.....................................................................................................................................3 1.4.1 Select....................................................................................................................................................3 1.4.2 SelectMany...........................................................................................................................................4 1.5 Partitioning operators..................................................................................................................................5 1.5.1 Take......................................................................................................................................................5 1.5.2 Skip.......................................................................................................................................................5 1.5.3 TakeWhile.............................................................................................................................................6 1.5.4 SkipWhile.............................................................................................................................................6 1.6 Join operators..............................................................................................................................................7 1.6.1 Join.......................................................................................................................................................7 1.6.2 GroupJoin.............................................................................................................................................8 1.7 Concatenation operator................................................................................................................................9 1.7.1 Concat...................................................................................................................................................9 1.8 Ordering operators.....................................................................................................................................10 1.8.1 OrderBy / ThenBy...............................................................................................................................10 1.8.2 Reverse...............................................................................................................................................11 1.9 Grouping operators....................................................................................................................................12 1.9.1 GroupBy.............................................................................................................................................12 1.10 Set operators............................................................................................................................................13 1.10.1 Distinct..............................................................................................................................................13 1.10.2 Union................................................................................................................................................13 1.10.3 Intersect.............................................................................................................................................14 1.10.4 Except...............................................................................................................................................14 1.11 Conversion operators...............................................................................................................................14 1.11.1 ToSequence.......................................................................................................................................14 1.11.2 ToArray.............................................................................................................................................15 1.11.3 ToList................................................................................................................................................15 1.11.4 ToDictionary.....................................................................................................................................15 1.11.5 ToLookup.........................................................................................................................................16 1.11.6 OfType..............................................................................................................................................17 1.11.7 Cast...................................................................................................................................................17 1.12 Equality operator.....................................................................................................................................18 1.12.1 EqualAll............................................................................................................................................18 1.13 Element operators....................................................................................................................................18 1.13.1 First...................................................................................................................................................18 1.13.2 FirstOrDefault...................................................................................................................................19 1.13.3 Last...................................................................................................................................................19 1.13.4 LastOrDefault...................................................................................................................................19 1.13.5 Single................................................................................................................................................20 1.13.6 SingleOrDefault................................................................................................................................20 1.13.7 ElementAt.........................................................................................................................................20 1.13.8 ElementAtOrDefault.........................................................................................................................21 1.13.9 DefaultIfEmpty.................................................................................................................................21

Copyright © Microsoft Corporation 2006. All Rights Reserved.

iii

...................................................................................................2 LongCount............................................................................................................15 Quantifiers..........................................................................16.........................................................................................................................22 1................................15................................................14...1 Count..........................................3 Contains....................................................Standard Query Operators 1......................................................25 1.....................................26 1..................................16....15...............23 1...................25 1...........6 Average.......................3 Sum................................................1 Range....... .............................22 1.......................................................5 Max...........................................................................................................................................................22 1......................................................................16 Aggregate operators..................................................................................................................................21 1...............................................................................24 1............................................................................................................................16.............................15..16.....................14.................................................22 1.........................................................2 All........................16.....................27 iv Copyright © Microsoft Corporation 2006.....23 1......................................................................................3 Empty................................................................................16...........................................1 Any.....................................23 1.................2 Repeat..............14.....21 1...................................................24 1...................................23 1................................................... All Rights Reserved............4 Min........................16...........14 Generation operators............................7 Aggregate............................................................................................................................

publ i c str i ng City . publ i c str i ng Region. lambda expressions. 1 . Technical Specification The Standard Query Operators is an API that enables querying of any . publ i c str i ng Name.Query. publ i c decimal Tota l . } publ i c class Product { publ i c int Product ID. publ i c str i ng Posta lCode. The future releases of C# 3. While not required. publ i c str i ng Name. Any object that implements the interface IEnumerable<T> for some type T is considered a sequence of that type. The Standard Query Operators operate on sequences. } Copyright © Microsoft Corporation 2006.dll. The examples refer to the following classes: publ i c class Customer { publ i c int CustomerID.Chapter 1 Technical Specification 1. publ i c str i ng Phone.0 will include these features.Sequencestatic class in the assembly named System. publ i c DateTime OrderDate.0 and VB 9. publ i c int Units InStock. All Rights Reserved.0 Common Language Specification (CLS) and is usable with any . publ i c str i ng Category. publ i c List Order> Orders. The Standard Query Operators API complies with the .Query. and native query syntax. publ i c str i ng Country. < } publ i c class Order { publ i c int OrderID.Query. the experience of using the Standard Query Operators is significantly enhanced with languages that support extension methods. The Standard Query Operators API consists of the methods declared in the System.NET array or collection. publ i c str i ng Address.NET 2. publ i c Customer Customer. The examples shown in this specification are all written in C# 3.0 and assume that the Standard Query Operators have been imported with the using clause: using System. publ i c int CustomerID. publ i c decimal UnitPr i ce .NET Language that supports generics.

0 Language Specifications. publ i c delegate TR Func<TR>(). TR>(T0 a0).0 and VB 9. publ i c stat i cIEnumerable<T> Where<T>( th is IEnumerable<T> source. In each of the Func types.3 Restriction operators 1. int. The local variable is assigned an anonymous method that returns true if the given customer is located in London. publ i c stat i cIEnumerable<T> Where<T>( th is IEnumerable<T> source. T2. publ i c delegate TR Func<T0. T3 a3). T2. < Lis t Product products = GetProductL i s t ( ) . T3.Where(predicate ) . publ i c delegate TR Func<T0.Funcfamily of generic delegate types can be used to construct delegate types “on the fly”. TR>(T0 a0. T1. bool> predicate = c => c. Func<T.C i ty == "London". publ i c delegate TR Func<T0. All Rights Reserved. and T3 type parameters represent argument types and the TR type parameter represents the result type. T2 a2. The example below declares a local variable predicate of a delegate type that takes a Customer and returns bool. the T0. . < > 1. T1. bool> predicate) .1 The Func delegate types The System. For further details on extension methods. TR>(T0 a0.3. 1. 2 Copyright © Microsoft Corporation 2006. Func<T. Taken together. The remaining sections of this chapter discusses these methods.Sequence static class declares a set of methods known as the Standard Query Operators. IEnumerable<Customer> customersInLondon = customers. The delegate referenced by predicate is subsequently used to find all the customers in London.2 The Sequence class The System. TR>(T0 a0. Func<Customer. < Lis t Order> orders = GetOrderL i s t ( ) . T2.Query. publ i c delegate TR Func<T0. T2 a2). bool> predicate) . T1 a1.1 Where The Where operator filters a sequence based on a predicate. The majority of the Standard Query Operators are extension methods that extend IEnumerable<T>.Query. T1 a1. the methods compose to form a complete query language for arrays and collections that implement IEnumerable<T>. 1. T1.Standard Query Operators The examples furthermore assume the existence of the following three variables: Lis t Customer> customers = GetCustomerLis t ( ) . please refer to the C# 3. T1 a1). thus eliminating the need for explicit delegate type declarations. T1.

> In a C# 3. publ i c stat i cIEnumerable<S> Select<T. it enumerates the source sequence and yields those elements for which the predicate function returns true. a selectclause translates to an invocation of Select The example above is . S> selector ) . it enumerates the source sequence and yields the results of evaluating the selector function for each element. Func<T. int. if present. is When the object returned by Where is enumerated.0 query expression. 3 .4 Projection operators 1. The first argument of the predicate function represents the element to test. a where clause translates to an invocation of Where . S> selector ) .4.1 Select The Selectoperator performs a projection over a sequence. represents the zero based index of the element within the source sequence.0 query expression. The Selectoperator allocates and returns an enumerable object that captures the arguments passed to the operator. > The following example creates a list of objects containing the name and price of each product with a price greater than or equal to 10: Copyright © Microsoft Corporation 2006. The second argument. if present.Chapter 1 Technical Specification The Where operator allocates and returns an enumerable object that captures the arguments passed to the operator. The following example creates a sequence of those products that have a price greater than or equal to 10: IEnumerable<Product x = products . An ArgumentNul lExcept ion thrown if either argument is null. An ArgumentNul lExcept ion thrown if either argument is null. represents the zero based index of the element within the source sequence.Uni tPr i ce >= 10 selectp. The example above is equivalent to the translation of IEnumerable<Product x = > from pin products where p. The first argument of the selector function represents the element to process. Func<T. The following example creates a sequence of the names of all products: IEnumerable<str i ng productNames = products . S>( th is IEnumerable<T> source.Uni tPr i ce >= 10). publ i c stat i cIEnumerable<S> Select<T. S>( th is IEnumerable<T> source. 1.Name).Se lec t (p => p. The second argument. All Rights Reserved. > In a C# 3. equivalent to the translation of IEnumerable<str i ng productNames = from pin productsselect p.Name.Where(p => p. is When the object returned by Selectis enumerated.

Standard Query Operators var namesAndPrices = products . index) . Select (p => new { p.Name. The following example creates a sequence of the orders of the customers in Denmark: IEnumerable<Order> orders = customers. is When the object returned by SelectManyis enumerated.Orders) . IEnumerable<List<Order>> instead of IEnumerable<Order>. .Order ID }). All Rights Reserved. if the relationship was unidirectional). and enumerates and yields the elements of each such enumerable object. Where(c => c. The first argument of the selector function represents the element to process. Select ( (p roduct . int. 1. maps each element to an enumerable object using the selector function. if present. o. SelectMany(c => c. An ArgumentNul lExcept ion thrown if either argument is null. the Customer property is used to “navigate back” to fetch the Name property of the order’s customer. index) new { product . index }).Country == "Denmark") . The following example creates a sequence of the indices of those products that have a price greater than or equal to 10: IEnumerable<int> ind ices = products . Select(o => new { o.4.product . Where(p => p.Name. publ i c stat i cIEnumerable<S> SelectMany<T.Uni tPr i ce >= 10). it enumerates the source sequence. If an order had no Customer property (i. ToLis t ( ) .e. Select (x => x. represents the zero based index of the element within the source sequence. The following example creates a sequence of objects containing the customer name and order ID of the orders in 2005 of the customers in Denmark: var namesAndOrderIDs = customers.OrderDate. Where(o => o.2 SelectMany The SelectManyoperator performs a one to many element projection over a sequence.Uni tPr i ce }). => Where(x => x. S>( th is IEnumerable<T> source. publ i c stat i cIEnumerable<S> SelectMany<T. an 4 Copyright © Microsoft Corporation 2006. Func<T. p. IEnumerable<S>> selector ) . S>( th is IEnumerable<T> source.Year == 2005). Func<T. The SelectManyoperator allocates and returns an enumerable object that captures the arguments passed to the operator. SelectMany(c => c. IEnumerable<S>> selector ) .Country == "Denmark").Customer. Where(c => c.Uni tP r i ce >= 10). The second argument.Orders). If the query had used Selectinstead of SelectMany the result would have been of type . In the example above.

OrderDate. Where(o => o. The Take and Skip operators are functional complements: For a given sequence s.Skip(n) yields the same sequence as s. example above is equivalent to the translation of var namesAndOrderIDs = from c in customers where c. Where(c => c. o.Order ID }) ).Name. 1. 1.OrderDate.Take(n) and s.Name.Country == "Denmark" from oin c.Order ID }.OrderByDescending(p => p. int count) . o. all but the initial from clause translate to invocations of SelectMany The . In a C# 3.5.Country == "Denmark") . Copyright © Microsoft Corporation 2006.Chapter 1 Technical Specification alternative solution is to rewrite the query.5. is When the object returned by Take is enumerated. the concatenation of s.1 Take The Take operator yields a given number of elements from a sequence and then skips the remainder of the sequence. in scope such that it can be referenced in the final Select : var namesAndOrderIDs = customers. Take(10) .Year == 2005). c.Year == 2005 selectnew { c.0 query expression. All Rights Reserved. keeping the current customer. it enumerates the source sequence and yields elements until the number of elements given by the count argument have been yielded or the end of the source is reached. publ i c stat i cIEnumerable <T> Take<T>( th is IEnumerable <T> source.Orders .Orders where o. SelectMany(c => c. the source sequence is not enumerated and no elements are yielded. 5 .2 Skip The Skip operator skips a given number of elements from a sequence and then yields the remainder of the sequence. An ArgumentNul lExcept ion thrown if the source argument is null. int count) . Select (o => new { c.5 Partitioning operators 1. The Take operator allocates and returns an enumerable object that captures the arguments passed to the operator.Uni tPr i ce ) . The following example creates a sequence of the most expensive 10 products: IEnumerable<Product MostExpensive10 = > products . If the count argument is less than or equal to zero. publ i c stat i cIEnumerable<T> Skip<T>( th is IEnumerable<T> source.

1. . publ i c stat i cIEnumerable<T> TakeWhile<T>( th is IEnumerable<T> source. When the object returned by TakeWhile is enumerated. publ i c stat i cIEnumerable<T> SkipWhi le<T>( th is IEnumerable<T> source.5. Func<T. The enumeration stops when the predicate function returns false or the end of the source sequence is reached. All Rights Reserved. if present. Func<T. Func<T. it enumerates the source sequence. the concatenation of s. publ i c stat i cIEnumerable<T> TakeWhile<T>( th is IEnumerable<T> source.Take(n) and s. Func<T.5. The second argument.3 TakeWhile The TakeWhile operator yields elements from a sequence while a test is true and then skips the remainder of the sequence. The following example creates a sequence of all but the most expensive 10 products: IEnumerable<Product Al lButMostExpensive10 = > products . is When the object returned by Skip is enumerated. If the count argument is less an or equal to zero. The Take and Skip operators are functional complements: Given a sequence s. An ArgumentNullException is thrown if either argument is null. int. represents the zero based index of the element within the source sequence. 6 Copyright © Microsoft Corporation 2006. The first argument of the predicate function represents the element to test.4 SkipWhile The SkipWhile operator skips elements from a sequence while a test is true and then yields the remainder of the sequence. The TakeWhile and SkipWhile operators are functional complements: Given a sequence s and a pure function p.TakeWhile(p) and s. bool> predicate) . bool> predicate) . nothing is yielded.OrderByDescending(p => p. all elements of the source sequence are yielded. skipping the number of elements given by the count argument and yielding the rest. it enumerates the source sequence. bool> predicate) . If the source sequence contains fewer elements than given by the count argument.Standard Query Operators The Skip operator allocates and returns an enumerable object that captures the arguments passed to the operator. testing each element using the predicate function and yielding the element if the result was true. int. The TakeWhile operator allocates and returns an enumerable object that captures the arguments passed to the operator.Skip(n) is the same sequence as s. The SkipWhile operator allocates and returns an enumerable object that captures the arguments passed to the operator. An ArgumentNullException is thrown if either argument is null. Sk i p (10) . bool> predicate) . 1.Uni tPr i ce ) . the concatenation of s. An ArgumentNul lExcept ion thrown if the source argument is null.SkipWhile(p) is the same sequence as s. publ i c stat i cIEnumerable<T> SkipWhi le<T>( th is IEnumerable<T> source.

a join clause translates to an invocation of Join. represents the zero based index of the element within the source sequence. V>( th is IEnumerable <T> outer . The second argument.SkipWhile(p) is the same sequence as s. it enumerates the source sequence. V> resul tSe lec tor ) . K> innerKeySelector .1 Join The Join operator performs an inner join of two sequences based on matching keys extracted from the elements. the resultSelector function is evaluated for the outer and inner element pair. respectively. The Join operator allocates and returns an enumerable object that captures the arguments passed to the operator. publ i c stat i cIEnumerable <V> Jo in<T. If the predicate function returns true for all elements in the sequence. the Join operator implements an inner equijoin. Func<U. no elements are yielded.6. o => o. the outerKeySelector function is evaluated and the resulting key is used to look up the corresponding inner elements in the hash table. The example above is equivalent to the translation of Copyright © Microsoft Corporation 2006.Name. K. 7 . and order total: var custOrders = customers. such as left outer join and right outer join have no dedicated standard query operators. producing a sequence of tuples with customer name. the outer sequence is enumerated. o. The first argument of the predicate function represents the element to test. The Join operator preserves the order of the outer sequence elements. and for each outer element. testing each element using the predicate function and skipping the element if the result was true. collecting the elements by their keys in a hash table. (c. In a C# 3. The TakeWhile and SkipWhi leoperators are functional complements: Given a sequence s and a pure function p. that element and the remaining elements are yielded with no further invocations of the predicate function. U. Once all inner elements and keys have been collected. if present. o) => new { c.CustomerID.OrderDate. it first enumerates the inner sequence and evaluates the innerKeySelector function once for each inner element. An ArgumentNullException is thrown if any argument is null. For each matching inner element (if any).6 Join operators 1. K> outerKeySelector . Join(orders. Func<T. For each outer element.Chapter 1 Technical Specification When the object returned by SkipWhi leis enumerated. In relational database terms. U. The resultSelector argument specifies a function that creates a result element from two matching outer and inner sequence elements. Func<T.CustomerID. c => c.0 query expression. Other join operations. order date. 1. All Rights Reserved. When the object returned by Join is enumerated. and the resulting object is yielded.Tota l } ). the concatenation of s.TakeWhile(p) and s. o. the order of the matching inner sequence elements. but are subsets of the capabilities of the GroupJoin operator. IEnumerable <U> inner . Once the predicate function returns false for an element. The outerKeySelector and innerKeySelector arguments specify functions that extract the join key values from elements of the outer and inner sequences. The following example joins customers and orders on their customer ID property.

c => c. the outerKeySelector function is evaluated.Name.OrderDate.CustomerID into co selectnew { c.Sum(o => o. V>( th is IEnumerable <T> outer .6. the order of the matching inner sequence elements. U. respectively.CustomerID.Tota l ) }. and the resulting object is yielded. The GroupJoinoperator allocates and returns an enumerable object that captures the arguments passed to the operator. the resulting key is used to look up the corresponding inner elements in the hash table. o. V> resul tSe lec tor ) . The resultSelector argument specifies a function that creates a result element from an outer sequence element and its matching inner sequence elements. The GroupJoin operator produces hierarchical results (outer elements paired with sequences of matching inner elements) and has no direct equivalent in traditional relational database terms. the outer sequence is enumerated. is The outerKeySelector innerKeySelector and arguments specify functions that extract the join key values from elements of the outer and inner sequences.Standard Query Operators var custOrders = from c in customers jo in oin orders on c.0 query expression. . o => o. IEnumerable <U> inner . K> outerKeySelector .CustomerID equals o.Name. The example above is equivalent to the translation of var custTotalOrders = from c in customers jo in oin orders on c. For each outer element. the resultSelector function is evaluated for the outer element and the (possibly empty) sequence of matching inner elements.Sum(o => o. producing a sequence of tuples with customer name and total of all orders: var custTotalOrders = customers. co) => new { c. Once all inner elements and keys have been collected. TotalOrders = co.Tota l ) ). For example. Func<T. publ i c stat i cIEnumerable <V> GroupJo in<T. a join…into clause translates to an invocation of GroupJoin. Func<U. The GroupJoin operator preserves the order of the outer sequence elements.Name.CustomerID selectnew { c. An ArgumentNul lExcept ion thrown if any argument is null. it first enumerates the inner sequence and evaluates the innerKeySelector function once for each inner element.Tota l }. Tota lOrders = co.CustomerID equals o. When the object returned by GroupJoin is enumerated. } In a C# 3. o. K> innerKeySelector . the inner join 8 Copyright © Microsoft Corporation 2006. collecting the elements by their keys in a hash table. All Rights Reserved. (c. Func<T. The following example performs a grouped join of customers with their orders.CustomerID. 1. The GroupJoin operator implements a superset of inner joins and left outer joins—both can be written in terms of grouped joins. IEnumerable <U>. Join(orders. K. and for each outer element.2 GroupJoin The GroupJoinoperator performs a grouped join of two sequences based on matching keys extracted from the elements.

yielding each element. Concat(customers. where emptyOrder is an Order instance used to represent a missing order. Dist i nc t ( ) . An ArgumentNul lExcept ion thrown if either argument is null.OrderDate.7 Concatenation operator 1. o. o. and then enumerates the second sequence.Name. The following example extracts all distinct locations from the addresses of all customers: IEnumerable<str i ng locat i ons = > customers. An alternate way of concatenating sequences is to construct a sequence of sequences (such as an array of sequences) and apply the SelectManyoperator with an identity selector function. The Concat operator allocates and returns an enumerable object that captures the arguments passed to the operator.Defaul t I f Empty(emptyOrder) selectnew { c.C i ty ) .Country) . o.Name. For example: IEnumerable<str i ng locat i ons = > new[] { customers.Region) . it enumerates the first sequence.Se lec t (c => c.Tota l }. customers. The query can be turned into a left outer join by applying the Defaul t I f Empty operator to the grouped orders var custTota lOrders = from c in customers jo in oin orders on c.Region)) . 9 .OrderDate. IEnumerable <T> second).Se lec t (c => c.Chapter 1 Technical Specification var custTota lOrders = from c in customers jo in oin orders on c.Tota l }.Se lec t (c => c.1 Concat The Concat operator concatenates two sequences.OrderDate. SelectMany(s => s) .Name. Concat(customers. }. o.Se lec t (c => c. All Rights Reserved.Se lec t (c => c.CustomerID into co from oin co selectnew { c. customers.CustomerID equals o.CustomerID selectnew { c.CustomerID equals o.Country) ) . can be written as a grouped join followed by an iteration of the grouped orders var custTota lOrders = from c in customers jo in oin orders on c.C i ty ) .Tota l }. Copyright © Microsoft Corporation 2006.CustomerID into co from oin co. is When the object returned by Concat is enumerated. yielding each element.Se lec t (c => c.CustomerID equals o. 1.7. publ i c stat i cIEnumerable <T> Concat<T>( th is IEnumerable <T> f i r s t . Dist i nc t ( ) . o. o.

publ i c stat i cOrderedSequence<T> OrderByDescending<T. from an element. Func<T.. . IComparer<K> comparer) .. An optional comparer for comparing key values.8 Ordering operators 1. 10 Copyright © Microsoft Corporation 2006. publ i c stat i cOrderedSequence<T> OrderBy<T. publ i c stat i cOrderedSequence<T> ThenBy<T. IComparer<K> comparer) . publ i c stat i cOrderedSequence<T> ThenBy<T. All Rights Reserved. the first ThenBy or ThenByDescending establishes the secondary ordering. Func<T.Standard Query Operators 1.. K>( th is OrderedSequence<T> source. The OrderBy.. K> keySelector . the second ThenBy or ThenByDescending establishes the tertiary ordering. A composition of the operators has the form source . K>( th is IEnumerable <T> source. where OrderBy(.. publ i c stat i cOrderedSequence<T> ThenByDescending<T.. publ i c stat i cOrderedSequence<T> OrderByDescending<T.). if any. K>( th is OrderedSequence<T> source. K> keySelector ) .. ThenBy(. K> keySelector ) . ThenBy. The initial OrderBy or OrderByDescending establishes the primary ordering. IComparer<K> comparer) . ThenBy(. Comparer<K>. publ i c stat i cOrderedSequence<T> OrderBy<T.) . K>( th is IEnumerable <T> source.Default. of type T. Each ordering is defined by: • • A keySelector function that extracts the key value. Func<T. K> keySelector . of type K. K> keySelector .) . is an invocation of ThenBy or ThenByDescending. Func<T. OrderBy(.. Func<T. publ i c stat i cOrderedSequence<T> ThenByDescending<T. and so on. IComparer<K> comparer) . K>( th is IEnumerable <T> source. K> keySelector . and ThenByDescending operators make up a family of operators that can be composed to order a sequence by multiple keys. OrderByDescending. K>( th is IEnumerable <T> source. is used. K>( th is OrderedSequence<T> source. K> keySelector ) .) is an invocation of OrderBy or OrderByDescending and each ThenBy(. If no comparer is specified of if the comparer argument is null...8.1 OrderBy / ThenBy The OrderBy / ThenBy family of operators order a sequence according to one or more keys. Func<T.) . K>( th is OrderedSequence<T> source. Func<T.. K> keySelector ) . the default comparer.. Func<T.

the order of the elements might not be preserved. and finally. OrderBy(p => p. it first enumerates source.Uni tPr i ce ) . Where(p => p. OrderBy(x => x). Copyright © Microsoft Corporation 2006. and ThenByDescending. yields the elements in the resulting order. The OrderBy and ThenBy methods establish an ascending ordering. collecting the key values to order by. then evaluates the keySelector function(s) once for each element. OrderByDescending. The following example creates a sequence of all products ordered first by category.Category. ThenByDescending(p => p.Name). then by descending price.Name i ce . OrderByDescending.Category == "Beverages").CurrentCul ture IgnoreCase). The OrderedSequence<T> class implements IEnumerable<T>.Chapter 1 Technical Specification • A sort direction. 11 . an orderby clause translates to invocations of OrderBy.0 query expression. but otherwise introduces no public members. ThenBy. OrderBy(p => p. IEnumerable<Product orderedProducts1 = > products . ThenBy(p => p. All Rights Reserved. When the object returned by one of the operators is enumerated.2 Reverse The Reverse operator reverses the elements of a sequence. then sorts the elements according to the collected key values and the characteristics of each ordering. the OrderByDescending and ThenByDescending methods establish a descending ordering. The OrderBy / ThenBy operators performs an unstable sort. if the key values of two elements are equal.Uni tPrdescending p. or ThenByDescending allocates and returns an enumerable object of type OrderedSequence<T> that captures the arguments passed to the operator. p. Str ingComparer. For example: IEnumerable<str i ng orderedProductNames = > products. ThenBy. In contrast. 1. that is.Category == "Beverages") .Name).Name. Where(p => p. and then by name. In a C# 3.Category) . An ArgumentNullException is thrown if the source or keySelector argument is null. collecting all elements. An invocation of OrderBy.8. To order a sequence by the values of the elements themselves. specify the identity key selector x => x. a stable sort preserves the order of elements that have equal key values. The following example creates a sequence of all beverage products ordered by case insensitive name: IEnumerable<Product orderedProducts2 = > products . selectp. Select(p => p. The example above is equivalent to the translation of IEnumerable<Product orderedProducts1 = > from pin products orderby p. publ i c stat i cIEnumerable<T> Reverse<T>( th is IEnumerable<T> source) .

EqualityComparer<K>. . E>> GroupBy<T. T> :IEnumerable < <T> { K Key {get. publ i c stat i cIEnumerable <IGrouping K. using the default equality comparer. E>( < th is IEnumerable <T> source. <K> publ i c stat i cIEnumerable <IGrouping K. publ i c stat i cIEnumerable <IGrouping K. and then yields the elements of the source sequence in reverse order. T>> GroupBy<T. may be null. Each IGrouping<K.Standard Query Operators The Reverse operator allocates and returns an enumerable object that captures the source argument. IEqualityComparer comparer) . is When the object returned by Reverse is enumerated. The comparer argument. An ArgumentNullException is thrown if any other argument is null. K> keySelector . The groupings are yielded in the order that their key values first occurred in the source sequence. a sequence of IGrouping<K. Func<T. E> instances are yielded. The following example groups all products by category: 12 Copyright © Microsoft Corporation 2006. All Rights Reserved. K> keySelector . if a null comparer was specified.Default. K>( < th is IEnumerable <T> source. and destination elements within a grouping are yielded in the order their source elements occurred in the source sequence. Func<T. If no elementSelector is specified. the source elements become the destination elements. Func<T. key values are compared using the given comparer. K. IEqualityComparer comparer) . K. Func<T.9 Grouping operators 1. T>> GroupBy<T. E>> GroupBy<T. publ i c stat i cIEnumerable <IGrouping K. Func<T. E> elementSelector ) .9. An ArgumentNul lExcept ion thrown if the source argument is null. When the object returned by GroupBy is enumerated. The elementSelector argument. K> keySelector .1 GroupBy The GroupBy operator groups the elements of a sequence. collecting all elements. it enumerates the source sequence. Once all key and destination element pairs have been collected. <K> publ i c inte r face IGrouping K. K> keySelector ) . E> elementSelector . The keySelector argument specifies a function that extracts the key value from a source element. it enumerates source and evaluates the keySelector and elementSelector (if present) functions once for each source element. Func<T. or. E>( < th is IEnumerable <T> source. E> instance represents a sequence of destination elements with a particular key value. K>( < th is IEnumerable <T> source. When creating the groupings. 1. specifies a function that maps a source element to a destination element. if present. } } The GroupBy operator allocates and returns an enumerable object that captures the arguments passed to the operator. if present.

and an ArgumentNullException is thrown if any element of a source sequence is null. The final product will not have this limitation.Category). The example above is equivalent to the translation of IEnumerable<IGrouping <stringstring productNamesByCategory = . 13 . publ i c stat i cIEnumerable<T> Dist i nc t<T>( th is IEnumerable<T> source) . An ArgumentNullException is thrown if the source argument is null.10. The Union operator allocates and returns an enumerable object that captures the arguments passed to the operator. in that order.GroupBy(p => p. Elements are compared using their GetHashCode and Equals methods. 1. IEnumerable<T> second). In a C# 3. Intersect. publ i c stat i cIEnumerable<T> Union<T>( th is IEnumerable<T> f i r s t . When the object returned by Distinct is enumerated. When the object returned by Union is enumerated.Select(p => p.Category.Chapter 1 Technical Specification IEnumerable<IGrouping <stringProduct . it enumerates the source sequence.Category.10 Set operators Note The May 2006 Technology Preview implementations of Dist i nc. The following example produces a sequence of all product categories: IEnumerable<str i ng productCategories = > products. Copyright © Microsoft Corporation 2006.Name). yielding each element that hasn’t previously been yielded.Category) . 1.Distinct().0 query expression. a group…by clause translates to an invocation of GroupBy. and Except do not support null elements. Elements are compared using their GetHashCode and Equals methods. >> productsByCategory = products . yielding each element that hasn’t previously been yielded.GroupBy(p => p. Note that the element and key selection expressions occur in the opposite order of the GroupBy operator. The following example groups all product names by product category: IEnumerable<IGrouping <stringstring productNamesByCategory = . An ArgumentNullException is thrown if any argument is null. p => p. All Rights Reserved. it enumerates the first and second sequences.Name by p. 1.tUnion.2 Union The Union operator produces the set union of two sequences.10. >> products .1 Distinct The Distinct operator eliminates duplicate elements from a sequence. The Distinct operator allocates and returns an enumerable object that captures the source argument. >> from pin products group p.

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.11 Conversion operators 1. it enumerates the first sequence.11.10. All Rights Reserved. for example because the predicate invokes a local method. marking those elements that occur in both sequences. is When the object returned by Intersect enumerated. the ToSequence operator can be used to hide Table<T>’s operators and instead make the Standard Query Operators available: 14 Copyright © Microsoft Corporation 2006. The Except operator allocates and returns an enumerable object that captures the arguments passed to the operator. For example. var query = custTable. collecting all distinct elements of that sequence. An ArgumentNullException is thrown if any argument is null. the query Table<Customer> custTable = GetCustomersTable(). When the object returned by Except is enumerated. 1.Standard Query Operators 1. collecting all distinct is elements of that sequence. removing those elements that were also contained in the first sequence. It then enumerates the second sequence. IEnumerable <T> second). Select. given a class Table<T> that implements IEnumerable<T> as well as its own Where. The operator has no effect other than to change the compile-time type of the source argument to IEnumerable<T>. It finally yields the remaining elements in the order in which they were collected. publ i c stat i cIEnumerable <T> Except<T>( th is IEnumerable <T> f i r s t . will invoke the public Where operator of Table<T>. It then enumerates the second sequence. Elements are compared using their GetHashCode and Equals methods. An ArgumentNul lExcept ion thrown if any argument is null.3 Intersect The Intersect operator produces the set intersection of two sequences. publ i c stat i cIEnumerable <T> Intersect<T>( th is IEnumerable <T> f i r s t . The Intersect operator allocates and returns an enumerable object that captures the arguments passed to the operator. and so on. The ToSequence operator simply returns the source argument. 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. If remote execution is not desired. 1. IEnumerable <T> second).4 Except The Except operator produces the set difference between two sequences. . it enumerates the first sequence. It finally yields the marked elements in the order in which they were collected. SelectMany. Elements are compared using their GetHashCode and Equals methods.Where(c => IsGoodCustomer(c)).1 ToSequence The ToSequence operator returns its argument typed as IEnumerable<T>. publ i c stat i cIEnumerable <T> ToSequence<T>( th is IEnumerable <T> source) .10.

ToSequence() . T> ToDict ionary<T. An ArgumentNul lExcept ion thrown if the source argument is null.3 ToList The ToListoperator creates a Lis t<T>from a sequence. E>( this IEnumerable<T> source. Where(c => c.Chapter 1 Technical Specification Table<Customer> custTable = GetCustomersTable().Orders . is The following example produces an array of the names of all countries in which there are customers: string[ ] customerCountr ies = customers. Func<T. public static Dictionary<K. Func<T. public static Dictionary<K. K> keySelector . public static List<T> ToLis t<T>( this IEnumerable<T> source) .OrderDate. 1.D i s t i nc t ( ) .Year == 2005)) .2 ToArray The ToArray operator creates an array from a sequence. An ArgumentNullException is thrown if the source argument is null. This would now cause the query to execute locally. 1. Func<T. The ToArray operator enumerates the source sequence and returns an array containing the elements of the sequence. E> ToDict ionary<T. The ToListoperator enumerates the source sequence and returns a Lis t<T>containing the elements of the sequence.11.Country) . 15 . public static T[] ToArray<T>( this IEnumerable<T> source) . K. All Rights Reserved. E> elementSelector ) . Func<T.Se lec t (c => c. Copyright © Microsoft Corporation 2006. K>( this IEnumerable<T> source. IEqualityComparer<K> comparer) .Where(c => IsGoodCustomer(c) ) .11. ToAr ray( ) . public static Dictionary<K.11. K>( this IEnumerable<T> source. var query = custTable . K> keySelector ) . K> keySelector . ToLis t ( ) . T> ToDict ionary<T.4 ToDictionary The ToDictionary operator creates a Dictionary<K. 1.Any(o => o. The following example produces a List<Customer> containing those customers that placed orders in 2005: List< Customer> customersWithOrders In2005 = customers.E> from a sequence.

Standard Query Operators public static Dictionary<K. E> ToDictionary<T. T> ToLookup<T. key values are compared using the given comparer. K> keySelector . K>( this IEnumerable<T> source. E> ToLookup<T. Func<T. If no elementSelector was specified. Func<T.Max(p => p. T> from a sequence. IEqualityComparer<K> comparer). K> keySelector ) . An ArgumentNullException is thrown if the source. K> keySelector.Category) . Func<T. E> elementSelector .Order ID) . All Rights Reserved.Group. decimal> categoryMaxPr ice = products . Func<T.Order> that maps from order ID to order for all orders in 2005: Dictionary< int.Uni tPr i ce ) ) . or elementSelector argument is null or if a key value produced by keySelector is null. 1. Func<T. An ArgumentException is thrown if keySelector produces a duplicate key value for two elements. public static Lookup<K. E> ToLookup<T.Year == 2005). SelectMany(c => c. ToDict ionary(g => g. . keySelector. Func<T.E>. K. K> keySelector .Default. public static Lookup<K. The following example creates a Dictionary<int. IEqualityComparer<K> comparer) . In the resulting dictionary. E> elementSelector. if a null comparer was specified. The ToDict i onary operator enumerates the source sequence and evaluates the keySelectorand elementSelector functions for each element to produce that element’s key and value. EqualityComparer<K>. Order> orders = customers. public static Lookup<K. K. E>( this IEnumerable<T> source. Where(o => o. E> elementSelector ) . K> keySelector . ToDict ionary(o => o. 16 Copyright © Microsoft Corporation 2006. the value for each element is simply the element itself.Key. The following example creates a Dictionary<string.5 ToLookup The ToLookup operator creates a Lookup<K. Func<T. GroupBy(p => p.decimal> that maps from category name to the maximum product price in that category: Dictionary< string. IEqualityComparer<K> comparer) .11. using the default equality comparer. or. K. public static Lookup<K. g => g.Orders) . K>( this IEnumerable<T> source. Func<T. E>( this IEnumerable<T> source. E>( this IEnumerable<T> source. The resulting key and value pairs are returned in a Dictionary<K.OrderDate. T> ToLookup<T.

GroupJoin.11. T> : IEnumerable<IGrouping<K. T>> GetEnumerator(). 17 . The functionality provided by Lookup<K. key values are compared using the given comparer. The resulting key and value pairs are returned in a Lookup<K.Chapter 1 Technical Specification public class Lookup<K.OfType<Employee>(). All Rights Reserved. each element e for which e is T evaluates to true is yielded by evaluating (T)e. The OfType operator allocates and returns an enumerable object that captures the source argument. An ArgumentNullException is thrown if the source argument is null. T> implements a one-to-many dictionary that maps keys to sequences of values.E>. Given a class Employee that inherits from a class Person. public IEnumerator<IGrouping<K. An ArgumentNullException is thrown if the source. and GroupBy operators. IEnumerable< Employee> employees = persons. } public IEnumerable<T> this[K key] { get. Product> productsByCategory = products . Product> that maps from category name to the sequence of products in that category: Lookup< string. } Lookup<K. The Cast operator allocates and returns an enumerable object that captures the source argument. public static IEnumerable<T> OfType<T>( this IEnumerable source) . 1. If no elementSelector was specified. An ArgumentNullException is thrown if the source argument is null.7 Cast The Cast operator casts the elements of a sequence to a given type. 1. T> which implements a one-to-one dictionary that maps keys to single values. Specifically. EqualityComparer<K>.Category) .Default.6 OfType The OfType operator filters the elements of a sequence based on a type. Copyright © Microsoft Corporation 2006. } public bool Contains(K key). This contrasts with Dictionary<K. The following example creates a Lookup<string. if a null comparer was specified. When creating the Lookup<K. E>. The ToLookup operator enumerates the source sequence and evaluates the keySelector and elementSelector functions for each element to produce that element’s key and value. public static IEnumerable<T> Cast<T>( this IEnumerable source) . T>> { public int Count { get. or. keySelector. When the object returned by OfType is enumerated. the value for each element is simply the element itself.11. using the default equality comparer. or elementSelector argument is null. T> is used in the implementations of the Join. the following example returns all employees from a list of persons: List< Person> persons = GetLis tOfPersons( ) . it enumerates the source sequence and yields those elements that are of type T. IEnumerable< Product> beverages = productsByCategory["Beverage"] .ToLookup(p => p.

an explicitly typed iteration variable translates to an invocation of Cast. 1. An InvalidOperationException is thrown if no element matches the predicate or if the source sequence is empty. Cast<Order>().Year == 2005 select o. 1.13. IEnumerable<T> second).Standard Query Operators When the object returned by Cast is enumerated.OrderDate. bool> predicate) . An ArgumentNullException is thrown if either argument is null. Func<T. the method returns false. An InvalidCastException is thrown if an element in the sequence cannot be cast to type T. . 18 Copyright © Microsoft Corporation 2006. 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. public static T Fi rs t<T>( this IEnumerable<T> source) . IEnumerable< Order> orders In2005 = from Order o in objects where o. An ArgumentNullException is thrown if any argument is null. The method returns true if all corresponding elements compare equal and the two sequences are of equal length. the First operator simply returns the first element of the sequence. All Rights Reserved.12. In a C# 3.Object. The EqualAll operator enumerates the two source sequences in parallel and compares corresponding elements using the Equals static method in System. public static T Fi rs t<T>( this IEnumerable<T> source. IEnumerable< Order> orders In2005 = objects .OrderDate. Otherwise. it enumerates the source sequence and yields each element cast to type T.1 EqualAll The EqualAll operator checks whether two sequences are equal.12 Equality operator 1. but the Cast operator can be used to supply the missing type information: ArrayList objects = GetOrders( ) . For example. The Cast operator can be used to bridge between non-generic collections and the Standard Query Operators. the non-generic ArrayList doesn’t implement IEnumerable<T>. Where(o => o. The example above is equivalent to the translation of ArrayList objects = GetOrders( ) .1 First The First operator returns the first element of a sequence.0 query expression. public static bool EqualAl l<T>( this IEnumerable<T> f i r s t .13 Element operators 1.Year == 2005).

public static T Fi rs tOrDefaul t<T>( this IEnumerable<T> source) . defaul t (T is returned. or a default value if no element is found. Func<T. public static T LastOrDefaul t<T>( this IEnumerable<T> source) . or a default value if no element is found. An ArgumentNul lExcept ion thrown if any argument is null. Customer c = customers. bool> predicate) .Chapter 1 Technical Specification The following example returns the first customer with a given phone number: string phone = "206-555-1212". the LastOrDefaul t operator simply returns the last element of the sequence. An Inva l i dOperat ionExcept ion is is thrown if no element matches the predicate or if the source sequence is empty. an exception is thrown if no customer with the given phone number exists.3 Last The Last operator returns the last element of a sequence.13. 1. Copyright © Microsoft Corporation 2006. 1. If no element matches the predicate or if the is source sequence is empty. The Last operator enumerates the source sequence and returns the last element for which the predicate function returned true. ) 1.2 FirstOrDefault The Fi r s tOrDefaul t operator returns the first element of a sequence.Phone == phone).4 LastOrDefault The LastOrDefaul t operator returns the last element of a sequence. public static T LastOrDefaul t<T>( this IEnumerable<T> source. public static T Last<T>( this IEnumerable<T> source) . If no predicate function is specified. To instead return null when no element is found.13. The LastOrDefaul t operator enumerates the source sequence and returns the last element for which the predicate function returned true. All Rights Reserved. bool> predicate) . public static T Fi rs tOrDefaul t<T>( this IEnumerable<T> source. If no predicate function is specified. Func<T. use the Fi r s tOrDefaul t operator.13. the Fi r s tOrDefaul t operator simply returns the first element of the sequence. Func<T. An ArgumentNul lExcept ion thrown if any argument is null. If no predicate function is specified. public static T Last<T>( this IEnumerable<T> source.First(c => c. The Fi r s tOrDefaul t operator enumerates the source sequence and returns the first element for which the predicate function returns true. bool> predicate) . the Last operator simply returns the last element of the sequence. 19 . In the example above. The default value for reference and nullable types is null.

20 Copyright © Microsoft Corporation 2006. the SingleOrDefaul operator simply t returns the single element of the sequence. The following example returns the single customer with a given customer ID: int id = 12345.13. bool> predicate) .5 Single The Singleoperator returns the single element of a sequence. An ArgumentNul lExcept ion thrown if any argument is null. Customer c = customers. If no element matches the predicate or if the is source sequence is empty. All Rights Reserved. . If no predicate function is specified.CustomerID == id) . public static T Single<T>( this IEnumerable<T> source) . Func<T. An Inva l i dOperat ionExcept ion is is thrown if the source sequence contains more than one matching element.13. If no element matches the predicate or if the source sequence is empty. In the example above. An Inva l i dOperat ionExcept ion is is thrown if the source sequence contains no matching element or more than one matching element. bool> predicate) . int index) . public static T SingleOrDefaul t<T>( this IEnumerable<T> source) .Standard Query Operators An ArgumentNul lExcept ion thrown if any argument is null. The SingleOrDefaul operator enumerates the source sequence and returns the single element for which the t predicate function returned true. t 1. the Singleoperator simply returns the single element of the sequence. public static T ElementAt<T>( this IEnumerable<T> source.6 SingleOrDefault The SingleOrDefaul operator returns the single element of a sequence. To instead return null when no element is found.13. an exception is thrown if no customer or more than one customer with the given ID exists. defaul t (T is returned. If no predicate function is specified. The default value for reference and nullable types is null. The default value for reference and nullable types is null.S ing le (c => c. ) 1. 1. The Singleoperator enumerates the source sequence and returns the single element for which the predicate function returned true. public static T SingleOrDefaul t<T>( this IEnumerable<T> source.7 ElementAt The ElementAt operator returns the element at a given index in a sequence. public static T Single<T>( this IEnumerable<T> source. Func<T. use the SingleOrDefaul operator. or a default value if no element is t found. default(T) is returned. An ArgumentNul lExcept ion thrown if any argument is null.

and the element found at that position in the sequence is returned. the source sequence is enumerated until index elements have been skipped. public static IEnumerable<T> Defaul t I f Empty<T>( this IEnumerable<T> source.14. If so.OrderByDescending(p => p. The DefaultIfEmpty operator allocates and returns an enumerable object that captures the arguments passed to the operator. If the source sequence is empty. The default value for reference and nullable types is null. All Rights Reserved. default(T) is returned. a single element with the given default value is yielded. If the index is less than zero or greater than or equal to the number of elements in the sequence. public static IEnumerable<T> Defaul t I f Empty<T>( this IEnumerable<T> source) .13. An ArgumentOutOfRangeException is thrown if the index is less than zero or greater than or equal to the number of elements in the sequence. the source sequence’s implementation of IList<T> is used to obtain the element at the given index.1 Range The Range operator generates a sequence of integral numbers. When the object returned by DefaultIfEmpty is enumerated. E l ementAt(2) .2 for an example. int index) . An ArgumentNullException is thrown if the source argument is null.9 DefaultIfEmpty The DefaultIfEmpty operator supplies a default element for an empty sequence. Otherwise. default(T) is yielded in place of an empty sequence. T defaul tVa lue) . sequence’s implementation of IList<T> is used to obtain the element at the given index.8 ElementAtOrDefault The ElementAtOrDefault operator returns the element at a given index in a sequence. The default value for reference and nullable types is null.6. Otherwise.Uni tPr i ce ) . The following example obtains the third most expensive product: Product th i rdMostExpensive = products . the source . 21 . and the element found at that position in the sequence is returned.Chapter 1 Technical Specification The ElementAt operator first checks whether the source sequence implements IL i s t<T>If so.14 Generation operators 1. An ArgumentNullException is thrown if the source argument is null. The ElementAtOrDefault operator first checks whether the source sequence implements IList<T>. or a default value if the index is out of range. 1. The DefaultIfEmpty operator can be combined with a grouping join to produce a left outer join.13. it enumerates the source sequence and yields its elements. public static T ElementAtOrDefaul t<T>( this IEnumerable<T> source. Copyright © Microsoft Corporation 2006. See §1. 1. 1. If no default value argument is specified. An ArgumentNullException is thrown if the source argument is null. the source sequence is enumerated until index elements have been skipped.

The Repeat operator allocates and returns an enumerable object that captures the arguments. The following obtains an empty sequence of customers: IEnumerable< Customer> noCustomers = Sequence. When the object returned by Repeat is enumerated.ToArray( ) . The following example produces a long[] with 256 elements containing the value -1.2 Repeat The Repeat operator generates a sequence by repeating a value a given number of times.Empty<Customer>().Standard Query Operators public static IEnumerable<int> Range( int start. 1.Range(0. public static bool Any<T>( this IEnumerable<T> source) . 256). If no predicate function is specified the Any operator simply returns true if the source sequence contains any elements. The Range operator allocates and returns an enumerable object that captures the arguments. When the object returned by Empty is enumerated. bool> predicate) . public static IEnumerable<T> Repeat<T>( T element.14. it yields nothing.14.1 Any The Any operator checks whether any element of a sequence satisfies a condition. When the object returned by Range is enumerated. it yields count occurrences of element. int count) . 1.15 Quantifiers 1.ToArray( ) . long[ ] x = Sequence. 100). . public static bool Any<T>( this IEnumerable<T> source. All Rights Reserved.1L. An ArgumentOutOfRangeException is thrown if the specified count is less than zero. The following example produces an array of the squares of the numbers from 0 to 99: int[ ] squares = Sequence.3 Empty The Empty operator returns an empty sequence of a given type. 1. it yields count sequential integers starting with the value start. 22 Copyright © Microsoft Corporation 2006. The Empty operator caches a single empty sequence of the given type.15. public static IEnumerable<T> Empty<T>(). The Any operator enumerates the source sequence and returns true if any element satisfies the test given by the predicate.Repeat( .MaxValue. Func<T. An ArgumentOutOfRangeException is thrown if count is less than zero or if start + count – 1 is larger than int. int count).Se lect (x => x * x) .

Func<T. the source sequence is enumerated to determine if it contains an element with the given value.3 Contains The Containsoperator checks whether a sequence contains a given element. The following example produces the names of the product categories for which all products are in stock: IEnumerable< string> fu l l yS tockedCategor ies = products . The Containsoperator first checks whether the source sequence implements ICol l ec t i on<T> so.1 Count The Count operator counts the number of elements in a sequence. An ArgumentNul lExcept ion thrown if any argument is null. An ArgumentNullException is thrown if the source argument is null.Uni ts InStock > 0)) .15. bool> predicate) . Select (g => g. An ArgumentNul lExcept ion thrown if any argument is null.Default. If Contains method in sequence’s implementation of ICollection<T> is invoked to obtain the result.2 All The Al l operator checks whether all elements of a sequence satisfy a condition. the enumeration of the source sequence is terminated at that point. GroupBy(p => p. 1.16.Group. Copyright © Microsoft Corporation 2006. EqualityComparer<K>. bool b = products .Uni ts InStock == 0). The elements and the given value are compared using the default equality comparer.Chapter 1 Technical Specification The enumeration of the source sequence is terminated as soon as the result is known. the . 23 .15. 1.Key). The Al l operator enumerates the source sequence and returns true if no element fails the test given by the predicate. If a matching element is found. Otherwise. public static bool Contains<T>( this IEnumerable<T> source.Any(p => p. is The following example checks whether any products with a price of 100 or more are out of stock. 1. public static int Count<T>( this IEnumerable<T> source) . The enumeration of the source sequence is terminated as soon as the result is known. This is consistent with established predicate logic and other query languages such as SQL.Al l ( p => p.Uni tPr i ce >= 100 && p.Category) . All Rights Reserved. is The Al l operator returns true for an empty sequence.16 Aggregate operators 1. public static bool Al l<T>( this IEnumerable<T> source. T value) . Where(g => g.

16. The Count operator with a predicate enumerates the source sequence and counts the number of elements for which the predicate function returns true. public static long LongCount<T>( this IEnumerable<T> source.16. the operator does not include null values in the result (null values can occur when the Numeric type is a nullable type). Func<T. and decimal?. 1. If the sum is too large to represent using the Numeric type. the source sequence is enumerated to count the number of elements. invokes the selector function for each element. The Sum operator enumerates the source sequence. public static long LongCount<T>( this IEnumerable<T> source) . for double and double?. and computes the sum of the resulting values.C i ty == "London") . If no selector function is specified. bool> predicate) . decimal. Numeric> selector ) . long. Otherwise. the sequence’s implementation of ICollection<T> is used to obtain the element count. For both Count operators. int?. and an OverflowException is thrown if the count exceeds int.MaxValue. The following example produces a sequence of customer names and order totals for a given year: 24 Copyright © Microsoft Corporation 2006. Func<T.Count(c => c. Func<T. long?. The Numeric type is one of int. Furthermore. bool> predicate). 1. the sum of the elements themselves is computed. For both Count operators. The LongCount operator enumerates the source sequence and counts the number of elements for which the predicate function returns true. an OverflowException is thrown or.2 LongCount The LongCount operator counts the number of elements in a sequence.3 Sum The Sum operator computes the sum of a sequence of numeric values. double?. public static Numeric Sum<T>( this IEnumerable<T> source. an ArgumentNullException is thrown if any argument is null. public static Numeric Sum( this IEnumerable< Numeric> source) . All Rights Reserved.Standard Query Operators public static int Count<T>( this IEnumerable<T> source. double. The following example returns the number of customers in London: int count = customers. An ArgumentNullException is thrown if any argument is null. The count of elements is returned as a value of type long. The Count operator without a predicate first checks whether the source sequence implements ICol l ec t i on<T> . If so. The Sum operator returns zero for an empty sequence. If no predicate function is specified the LongCount operator simply counts all elements. an ArgumentNullException is thrown if any argument is null. a positive or negative infinity is returned. .

1.Group. double?. decimal. public static T Min<T>( this IEnumerable<T> source) . public static Numeric Min( this IEnumerable< Numeric> source) . public static Numeric Max( this IEnumerable< Numeric> source) . GroupBy(p => p. Furthermore. Copyright © Microsoft Corporation 2006. if the values do not implement that interface. the Min operators for int?.5 Max The Max operator finds the maximum of a sequence of numeric values. TotalOrders = c. or.4 Min The Min operator finds the minimum of a sequence of numeric values.Year == year).Key.Min(p => p.Total) }). double. the minimum of the elements themselves is computed. and decimal? return null if the source sequence is empty or contains only null values. var namesAndTotals = customers. invokes the selector function for each element.16.Category) . double?. 25 . the non-generic IComparable interface. MinPr ice = g. Select(c => new { c. long?. S>( this IEnumerable<T> source.OrderDate. . public static S Min<T. Where(o => o.Orders. Sum(o => o.16. If no selector function is specified. Func<T. 1. Func<T. The values are compared using their implementation of the IComparable<T> interface. The Numeric type is one of int. Select (g => new { Category = g.Uni tPr i ce ) }). int? long. The Min implementations for the Numeric types are optimizations of the more general generic operators. S> selector ) . The other Min operators throw an InvalidOperationException if the source sequence is empty. An ArgumentNullException is thrown if any argument is null. The Min operator enumerates the source sequence. and decimal?. long?. All Rights Reserved. Numeric> selector ) . and finds the minimum of the resulting values. public static Numeric Min<T>( this IEnumerable<T> source. The following example produces a sequence of name and lowest product price for each product category: var minPr iceByCategory = products .Name.Chapter 1 Technical Specification int year = 2005.

The Max operator enumerates the source sequence. Where(o => o. and decimal?. If no selector function is specified. Max(o => o. the average of the elements themselves is computed.16. The Numeric type is one of int. The Numeric type is one of int. All Rights Reserved. public static S Max<T. double. The other Max operators throw an InvalidOperationException if the source sequence is empty. Numeric> selector). Func<T. public static Result Average( this IEnumerable< Numeric> source) .Year == 2005). S> selector). When the Numeric type is int or long. When the Numeric type is int? or long?. Func<T. long?. long?. long. The Average operator enumerates the source sequence. the non-generic IComparable interface. and computes the average of the resulting values. . and finds the maximum of the resulting values. The following example finds the total of the largest order in 2005: decimal la rgestOrder = customers. int?. double. decimal. For the Numeric types int. if the sum of the elements is too large to represent in a long. Furthermore. For the Numeric types decimal and decimal?. double?. Numeric> selector ) . .OrderDate. int?. the Result type is double?. or. An ArgumentNullException is thrown if any argument is null. public static Numeric Max<T>( this IEnumerable<T> source. public static Result Average<T>( this IEnumerable<T> source. an OverflowException is thrown. If no selector function is specified. The Max implementations for the Numeric types are optimizations of the more general generic operators.Tota l ) .Standard Query Operators public static T Max<T>( this IEnumerable<T> source). SelectMany(c => c. and decimal? return null if the source sequence is empty or contains only null values. long?. S>( this IEnumerable<T> source. the Result type is double. long. invokes the selector function for each element. 1. invokes the selector function for each element. Otherwise. an OverflowException is thrown.Orders) . the maximum of the elements themselves is computed. The values are compared using their implementation of the IComparable<T> interface. double?. double?. Func<T. and decimal?. if the values do not implement that interface. The following example computes the average order total for each customer: 26 Copyright © Microsoft Corporation 2006. the Numeric and Result types are the same. An ArgumentNullException is thrown if any argument is null. if the sum of the elements is too large to represent in a decimal. int? long. or long?. decimal.6 Average The Average operator computes the average of a sequence of numeric values. the Max operators for int?.

Select (p => p. U> func) . U>( this IEnumerable<T> source. Func<U. public static U Aggregate<T. The final accumulator value is returned as the result.Length > s. An ArgumentNul lExcept ion thrown if the is source or func argument is null.Orders. t) => t. Select(c => new { c. Func<T.Chapter 1 Technical Specification var averageOrderTotals = customers. public static T Aggregate<T>( this IEnumerable<T> source. the Aggregate operator without a seed value throws an InvalidOperationException. but otherwise functions as described above. All Rights Reserved.Total) }).Name. Copyright © Microsoft Corporation 2006. 27 . If the source sequence is empty. repeatedly computing the next accumulator value by invoking the specified function with the current accumulator value as the first argument and the current sequence element as the second argument. U seed. It then enumerates the source sequence. LongestName = g.Name).Average(o => o.7 Aggregate The Aggregate operator applies a function over a sequence. T> func) .Length ? t : s) }). Aggregate((s. T.Category) .16. GroupBy(p => p.Key. 1. AverageOrderTotal = c. The Aggregate operator with a seed value starts by assigning the seed value to an internal accumulator. Select (g => new { Category = g. T. The following example produces a sequence of category name and longest product name for each product category: var longestNamesByCategory = products .Group. The Aggregate operator without a seed value uses the first element of the source sequence as the seed value.

Sign up to vote on this title
UsefulNot useful