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

Create successful ePaper yourself

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

Chapter 8 ❘ 645<br />

The query orders its results by both the number of wins and the total number of points. Finally,<br />

it selects the team’s name together with the number of wins and total number of points.<br />

Next, the program loops through the query and displays the results. Because the query<br />

selects simple string and integer values, displaying the results is easy.<br />

6. Example program CreateVolleyballDataSet does this. The code is fairly long, so it isn’t<br />

shown here. Download the example to see the solution.<br />

7. Example program VolleyballTeamsAndPlayersDataSet does this.<br />

The program demonstrates two approaches. The following code shows the first approach.<br />

// Loop through the teams displaying them and their players.<br />

foreach (DataRow team in teamsTable.AsEnumerable())<br />

{<br />

// Display the team's name.<br />

Console.WriteLine(team.Field("TeamName"));<br />

// Select the team's players.<br />

string teamName = team.Field("TeamName");<br />

var players =<br />

from player in playersTable.AsEnumerable()<br />

where player.Field("TeamName") == teamName<br />

select player;<br />

}<br />

// Display the players.<br />

foreach (var player in players)<br />

Console.WriteLine(" " +<br />

player.Field("FirstName") + " " +<br />

player.Field("LastName"));<br />

This code loops through the records from the Teams table. (Note that the items returned<br />

by the table’s AsEnumerable method are DataRow objects. Note also that you could loop<br />

over the table’s Rows collection instead of using AsEnumerable.)<br />

For each team, the program displays the team’s name, selects the corresponding records in<br />

the Players table, and displays the selected players.<br />

The program’s second approach uses the following code.<br />

// Select the teams joined with the players.<br />

var teams =<br />

from team in teamsTable.AsEnumerable()<br />

join player in playersTable.AsEnumerable()<br />

on team.Field("TeamName") equals player.Field("TeamName")<br />

group player by team into teamPlayers<br />

select teamPlayers;<br />

// Loop through the teams displaying them and their players.<br />

foreach (var team in teams)<br />

{<br />

// Display the team's name.<br />

Console.WriteLine(team.Key.Field("TeamName"));<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!