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.

linQ overview ❘ 271<br />

}<br />

{<br />

teams = new List()<br />

{<br />

new Team("Vanwall", 1958),<br />

new Team("Cooper", 1959, 1960),<br />

new Team("Ferrari", 1961, 1964, 1975, 1976, 1977, 1979, 1982,<br />

1983, 1999, 2000, 2001, 2002, 2003, 2004, 2007, 2008),<br />

new Team("BRM", 1962),<br />

new Team("Lotus", 1963, 1965, 1968, 1970, 1972, 1973, 1978),<br />

new Team("Brabham", 1966, 1967),<br />

new Team("Matra", 1969),<br />

new Team("Tyrrell", 1971),<br />

new Team("McLaren", 1974, 1984, 1985, 1988, 1989, 1990, 1991,<br />

1998),<br />

new Team("Williams", 1980, 1981, 1986, 1987, 1992, 1993, 1994,<br />

1996, 1997),<br />

new Team("Benetton", 1995),<br />

new Team("Renault", 2005, 2006 )<br />

};<br />

}<br />

return teams;<br />

linq query<br />

Using these prepared lists <strong>and</strong> entities, you can do a LINQ query, for example, a query to get all world<br />

champions from Brazil sorted by the highest number of wins. To accomplish this you could use methods of<br />

the List class; e.g. the FindAll() <strong>and</strong> Sort() methods. However, using LINQ there’s a simpler syntax<br />

as soon as you’re used to it:<br />

private static void LinqQuery()<br />

{<br />

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

where r.Country == "Brazil"<br />

orderby r.Wins descending<br />

select r;<br />

}<br />

foreach (Racer r in query)<br />

{<br />

Console.WriteLine("{0:A}", r);<br />

}<br />

code snippet LINQIntro/Program.cs<br />

The result of this query shows world champions from Brazil ordered:<br />

Ayrton Senna, Brazil; starts: 161, wins: 41<br />

Nelson Piquet, Brazil; starts: 204, wins: 23<br />

Emerson Fittipaldi, Brazil; starts: 143, wins: 14<br />

The statement<br />

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

where r.Country == "Brazil"<br />

orderby r.Wins descending<br />

select r;<br />

is a LINQ query. The clauses from, where, orderby, descending, <strong>and</strong> select are predefined keywords in<br />

this query.<br />

The query expression must begin with a from clause <strong>and</strong> end with a select or group clause. In between<br />

you can optionally use where, orderby, join, let, <strong>and</strong> additional from clauses.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!