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.

Chapter 14 ❘ 671<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 />

string value = Books[author];<br />

string[] books = value.Split(',');<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 />

It uses the Split method to split the value string into an array of book titles and sets the<br />

books ListBox’s DataSource property to the resulting array.<br />

4. The CarList example program does this. Download the example to see how it works.<br />

5. The ReverseList example program uses the following code to create and reverse its list<br />

of characters.<br />

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

{<br />

// Make the original list.<br />

List original = new List() { 'A', 'B', 'C', 'D', 'E' };<br />

originalListTextBox.Text = new string(original.ToArray());<br />

// LINQ.<br />

var linq =<br />

from char letter in original<br />

orderby letter descending<br />

select letter;<br />

linqTextBox.Text = new string(linq.ToArray());<br />

// Reverse.<br />

List reversed = new List(original);<br />

reversed.Reverse();<br />

reverseTextBox.Text = new string(reversed.ToArray());<br />

// Stack.<br />

Stack stack = new Stack();<br />

// Add the characters to the stack.<br />

foreach (char ch in original) stack.Push(ch);<br />

// Remove the characters from the stack.<br />

List result = new List();<br />

while (stack.Count > 0) result.Add(stack.Pop());<br />

}<br />

// Display the result.<br />

stackTextBox.Text = new string(result.ToArray());<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!