15.02.2015 Views

C# 4 and .NET 4

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

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

st<strong>and</strong>ard Query operators ❘ 275<br />

where n.StartsWith("J")<br />

orderby n<br />

select n).ToList();<br />

Console.WriteLine("First iteration");<br />

foreach (string name in namesWithJ)<br />

{<br />

Console.WriteLine(name);<br />

}<br />

Console.WriteLine();<br />

names.Add("John");<br />

names.Add("Jim");<br />

names.Add("Jack");<br />

names.Add("Denny");<br />

Console.WriteLine("Second iteration");<br />

foreach (string name in namesWithJ)<br />

{<br />

Console.WriteLine(name);<br />

}<br />

In the result, you can see that in between the iterations the output stays the same although the collection<br />

values have changed:<br />

First iteration<br />

Juan<br />

Second iteration<br />

Juan<br />

sT<strong>and</strong>ard query oPeraTors<br />

Where, OrderByDescending, <strong>and</strong> Select are only a few of the query operators defined by LINQ. The<br />

LINQ query defines a declarative syntax for the most common operators. There are many more query<br />

operators available with the Enumerable class.<br />

The following table lists the st<strong>and</strong>ard query operators defined by the Enumerable class:<br />

sT<strong>and</strong>ard query oPeraTors<br />

Where OfType<br />

Select SelectMany<br />

OrderBy ThenBy OrderByDescending<br />

ThenByDescending Reverse<br />

desCriPTion<br />

Filtering operators define a restriction to the elements returned.<br />

With the Where query operator you can use a predicate, for<br />

example, defined by a Lambda expression that returns a bool.<br />

OfType filters the elements based on the type <strong>and</strong><br />

returns only the elements of the type TResult.<br />

Projection operators are used to transform an object into a new<br />

object of a different type. Select <strong>and</strong> SelectMany define a<br />

projection to select values of the result based on a selector<br />

function.<br />

Sorting operators change the order of elements<br />

returned. OrderBy sorts values in ascending order;<br />

OrderByDescending sorts values in descending order.<br />

ThenBy <strong>and</strong> ThenByDescending operators are used for a<br />

secondary sort if the first sort gives similar results. Reverse<br />

reverses the elements in the collection.<br />

continues<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!