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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

670 ❘ APPENDIX A Solutions to Exercises<br />

}<br />

authorListBox.DataSource = authors.ToArray();<br />

This code uses LINQ to select the keys (author names). It converts the result into an array<br />

and displays the names by setting the author ListBox’s DataSource property.<br />

When the user clicks on an author, the following code displays that author’s book titles.<br />

// Display the books by the selected author.<br />

private void authorListBox_SelectedIndexChanged(object sender, EventArgs e)<br />

{<br />

string author = authorListBox.SelectedItem.ToString();<br />

List books = Books[author];<br />

booksListBox.DataSource = books;<br />

}<br />

This code gets the selected author’s name and then uses it to get the value for that author.<br />

The value is a List containing the author’s book titles. The program converts that<br />

into an array and displays the result in the book ListBox.<br />

3. The BookNameValueCollection example program uses the following code to create and<br />

initialize its NameValueCollection.<br />

// The book data.<br />

private NameValueCollection Books =<br />

new NameValueCollection<br />

{<br />

{"Stephen King",<br />

"Carrie,The Shining,The Stand"},<br />

{"Tom Clancy",<br />

"The Hunt for Red October,Red Storm Rising,Patriot Games"},<br />

{"Agatha Christie",<br />

"The Mysterious Affair at Styles,The Thirteen Problems"},<br />

};<br />

The collection’s initialization code contains three name/value pairs. The keys are author<br />

names. Each of the values is a string holding an author’s book titles separated by commas.<br />

When it loads, the program uses the following code to display the author names.<br />

// Display the authors.<br />

private void Form1_Load(object sender, EventArgs e)<br />

{<br />

var authors =<br />

from name in Books.AllKeys<br />

orderby name<br />

select name;<br />

authorListBox.DataSource = authors.ToArray();<br />

}<br />

This code uses LINQ to select the NameValueCollection’s keys (author names). It converts<br />

the result into an array and displays the names by setting the author ListBox’s<br />

DataSource property.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!