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.

Dictionaries ❘ 253<br />

application by entering X . If the key is in the dictionary, it is examined with the TryGetValue() method of<br />

the Dictionary < TKey, TValue > class. TryGetValue() returns true if the key is found <strong>and</strong> false otherwise.<br />

If the value is found, the value associated with the key is stored in the employee variable. This value is<br />

written to the console.<br />

You can also use an indexer of the Dictionary < TKey, TValue > class instead of<br />

TryGetValue() to access a value stored in the dictionary. However, if the key is not<br />

found, the indexer throws an exception of type KeyNotFoundException .<br />

while (true)<br />

{<br />

Console.Write("Enter employee id (X to exit) > ");<br />

var userInput = Console.ReadLine();<br />

userInput = userInput.ToUpper();<br />

if (userInput == "X") break;<br />

EmployeeId id;<br />

try<br />

{<br />

id = new EmployeeId(userInput);<br />

}<br />

}<br />

}<br />

Employee employee;<br />

if (!employees.TryGetValue(id, out employee))<br />

{<br />

Console.WriteLine("Employee with id {0} does not exist",<br />

id);<br />

}<br />

else<br />

{<br />

Console.WriteLine(employee);<br />

}<br />

}<br />

catch (EmployeeIdException ex)<br />

{<br />

Console.WriteLine(ex.Message);<br />

}<br />

Running the application produces the following output:<br />

lookup<br />

Enter employee id (X to exit) > C3386<br />

C003386: Jimmie Johnson 5.024.710,00<br />

Enter employee id (X to exit) > F3547<br />

F003547: Carl Edwards 5.597.120,00<br />

Enter employee id (X to exit) > X<br />

Press any key to continue …<br />

Dictionary < TKey, TValue > supports only one value per key. The class Lookup < TKey, TElement > resembles<br />

a Dictionary < TKey, TValue > but maps keys to a collection of values. This class is implemented in the<br />

assembly System.Core <strong>and</strong> defi ned with the namespace System.Linq .<br />

Lookup < TKey, TElement > cannot be created as a normal dictionary. Instead, you have to invoke<br />

the method ToLookup() that returns a Lookup < TKey, TElement > object. The method ToLookup()<br />

is an extension method that is available with every class implementing IEnumerable < T > . In the<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!