03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

182 ❘ CHAPTER 8 LINQ<br />

The following list summarizes LINQ’s aggregate methods.<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

Aggregate—Uses a method that you specify to perform some calculation on the values<br />

Average—Returns the average of the values<br />

Count—Returns the number of items that satisfy a condition<br />

Sum—Returns the sum of the values<br />

LongCount—Returns the number of items that satisfy a condition as a long<br />

Max—Returns the maximum value<br />

Min—Returns the minimum value<br />

Set Methods<br />

Set methods modify a set of items. For example, the Union method creates the union of two sets.<br />

<strong>C#</strong> does not provide a special syntax for including these methods in a LINQ query, so you must<br />

invoke the methods directly. Fortunately these methods are easy to use.<br />

For example, suppose the ordersPaid and ordersDue arrays contain Order objects representing<br />

customer orders that have been paid and that are due, respectively. The following statement uses<br />

the Union method to create a new array containing all the orders in both arrays.<br />

Order[] allOrders = ordersPaid.Union(ordersDue).ToArray();<br />

The result of the Union method is an iterator that you could loop over with a foreach statement.<br />

This example calls the result’s ToArray method to convert it into an array.<br />

You can apply these methods to the results of a query. For example, the following query examines<br />

the orders array and selects the Order objects’ CustomerId values. The code then uses the Distinct<br />

method to restrict the result to only distinct values. The following foreach statement displays the<br />

distinct values.<br />

var query =<br />

(from order in orders select order.CustomerId).Distinct();<br />

foreach (int id in query)<br />

Console.WriteLine(id);<br />

The following list summarizes LINQ’s set methods.<br />

Concat—Returns two result sets concatenated<br />

Distinct—Returns a set without duplicates<br />

Except—Returns the items in one set except those that are also in a second set<br />

Intersect—Returns the items that are in both of two set<br />

Union—Returns the items that are in either of two set<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!