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.

644 ❘ APPENDIX A Solutions to Exercises<br />

{<br />

}<br />

Console.WriteLine(string.Format(format, obj.Team, obj.Score));<br />

The query matches Team elements inside the Teams subtree with Team elements inside the<br />

Matches subtree. For each selected pair, the query selects the team’s Name attribute and<br />

the match result’s Score attribute.<br />

Notice that the code compares the team and match Name attributes after converting them<br />

into strings. The attributes themselves are XAttribute objects. They hold the same value<br />

but the XAttribute objects are different, so if you compare those objects you’ll never find<br />

any matches.<br />

After selecting the corresponding records, the program loops through the query’s results<br />

and displays the team names and scores.<br />

5. Example program VolleyballTeamsAndTotals does this. It uses the following code to calculate<br />

and display the teams’ total wins and points.<br />

// Select the teams and their results.<br />

// Total each team's wins and points.<br />

var teamResults =<br />

from team in root.Element("Teams").Descendants("Team")<br />

join result in root.Element("Matches").Descendants("Team")<br />

on team.Attribute("Name").Value<br />

equals result.Attribute("Name").Value<br />

group result by team into teamMatches<br />

orderby teamMatches.Count(r => r.Attribute("Score").Value == "25") descending,<br />

teamMatches.Sum(r => (int)r.Attribute("Score")) descending<br />

select new<br />

{<br />

Team = teamMatches.Key.Attribute("Name").Value,<br />

Wins = teamMatches.Count(r => r.Attribute("Score").Value == "25"),<br />

Points = teamMatches.Sum(r => (int)r.Attribute("Score"))<br />

};<br />

string format = "{0,-20}{1,10}{2,10}";<br />

Console.WriteLine(string.Format(format, "Name", "Wins", "Points"));<br />

Console.WriteLine(string.Format(format, "====", "====", "======"));<br />

foreach (var results in teamResults)<br />

{<br />

Console.WriteLine(string.Format(format,<br />

results.Team, results.Wins, results.Points));<br />

}<br />

Like the solution to Exercise 4, this program joins teams with match results. It groups the<br />

results by team and calls the groups teamMatches.<br />

To determine the number of matches a team won, the query counts the matches where the<br />

Score attribute has value 25.<br />

To determine a team’s total number of points, the query takes the sum of the match values’<br />

Score attribute values converted into integers.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!