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.

282 ❘ ChaPTer 11 lAnGuAGe inteGrAted Query<br />

join<br />

You can use the join clause to combine two sources based on specific criteria. But first, let’s get two lists<br />

that should be joined. With Formula-1, there’s a drivers <strong>and</strong> a constructors championship. The drivers<br />

are returned from the method GetChampions(), <strong>and</strong> the constructors are returned from the method<br />

GetConstructorChampions(). Now it would be interesting to get a list by year where every year lists the<br />

driver <strong>and</strong> the constructor champion.<br />

For doing this, the first two queries for the racers <strong>and</strong> the teams are defined:<br />

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

from y in r.Years<br />

where y > 2003<br />

select new<br />

{<br />

Year = y,<br />

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

};<br />

var teams = from t in<br />

Formula1.GetContructorChampions()<br />

from y in t.Years<br />

where y > 2003<br />

select new<br />

{<br />

Year = y,<br />

Name = t.Name<br />

};<br />

Using these two queries, a join is done based on the year of the driver champion <strong>and</strong> the year of the team<br />

champion with the clause join t in teams on r.Year equals t.Year. The select clause defines a<br />

new anonymous type containing Year, Racer, <strong>and</strong> Team properties:<br />

var racersAndTeams =<br />

from r in racers<br />

join t in teams on r.Year equals t.Year<br />

select new<br />

{<br />

Year = r.Year,<br />

Racer = r.Name,<br />

Team = t.Name<br />

};<br />

Console.WriteLine("Year Champion " + "Constructor Title");<br />

foreach (var item in racersAndTeams)<br />

{<br />

Console.WriteLine("{0}: {1,-20} {2}",<br />

item.Year, item.Racer, item.Team);<br />

}<br />

Of course you can also combine this to one LINQ query, but that’s a matter of taste:<br />

int year = 2003;<br />

var racersAndTeams =<br />

from r in<br />

from r1 in Formula1.GetChampions()<br />

from yr in r1.Years<br />

where yr > year<br />

select new<br />

{<br />

Year = yr,<br />

Name = r1.FirstName + " " + r1.LastName<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!