15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

286 ❘ ChaPTer 11 lAnGuAGe inteGrAted Query<br />

Jim Clark<br />

Page 1<br />

Juan Manuel Fangio<br />

Nino Farina<br />

Emerson Fittipaldi<br />

Mika Hakkinen<br />

Lewis Hamilton<br />

Page 2<br />

Mike Hawthorn<br />

Phil Hill<br />

Graham Hill<br />

Damon Hill<br />

Denny Hulme<br />

Paging can be extremely useful with Windows or web applications showing the user only a part of the data.<br />

An important behavior of this paging mechanism that you will notice: because the<br />

query is done with every page, changing the underlying data affects the results. New<br />

objects are shown as paging continues. Depending on your scenario this can be<br />

advantageous to your application. If this behavior is not what you need, you can do<br />

the paging not over the original data source, but by using a cache that maps to the<br />

original data.<br />

With the TakeWhile() <strong>and</strong> SkipWhile() extension methods you can also pass a predicate to take or skip<br />

items based on the result of the predicate.<br />

aggregate operators<br />

The aggregate operators such as Count() , Sum() , Min() , Max() , Average() , <strong>and</strong> Aggregate() do not<br />

return a sequence but a single value instead.<br />

The Count() extension method returns the number of items in the collection. Here the Count() method is<br />

applied to the Years property of a Racer to fi lter the racers <strong>and</strong> return only the ones who won more than<br />

three championships:<br />

The result is shown here:<br />

var query = from r in Formula1.GetChampions()<br />

where r.Years.Count() > 3<br />

orderby r.Years.Count() descending<br />

select new<br />

{<br />

Name = r.FirstName + " " + r.LastName,<br />

TimesChampion = r.Years.Count()<br />

};<br />

foreach (var r in query)<br />

{<br />

Console.WriteLine("{0} {1}", r.Name, r.TimesChampion);<br />

}<br />

Michael Schumacher 7<br />

Juan Manuel Fangio 5<br />

Alain Prost 4<br />

The Sum() method summarizes all numbers of a sequence <strong>and</strong> returns the result. Here, Sum() is used to<br />

calculate the sum of all race wins for a country. First the racers are grouped based on the country, then with<br />

the new anonymous type created, the Wins property is assigned to the sum of all wins from a single country:<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!