Книга: C# 2008 Programmer

Dictionary

Dictionary

Most of you are familiar with the term dictionary — a reference book containing an alphabetical list of words with information about them. In computing, a dictionary object provides a mapping from a set of keys to a set of values. In .NET, this dictionary comes in the form of the Dictionary class (the generic equivalent is Dictionary<T,V>).

The following shows how you can create a new Dictionary object with type int to be used for the key and type String to be used for the values:

Dictionary<int, string> employees = new Dictionary<int, string>();

To add items into a Dictionary object, use the Add() method:

employees.Add(1001, "Margaret Anderson");
employees.Add(1002, "Howard Mark");
employees.Add(1003, "John Smith");
employees.Add(1004, "Brian Will");

Trying to add a key that already exists in the object produces an ArgumentException error:

//---ArgumentException; duplicate key---
employees.Add(1004, "Sculley Lawrence");

A safer way is to use the ContainsKey() method to check if the key exists before adding the new key:

if (!employees.ContainsKey(1005)) {
 employees.Add(1005, "Sculley Lawrence");
}

While having duplicate keys is not acceptable, you can have different keys with the same value:

employees.Add(1006, "Sculley Lawrence"); //---duplicate value is OK---

To retrieve items from the Dictionary object, simply specify the key:

Console.WriteLine(employees[1002].ToString()); //---Howard Mark---

When retrieving items from a Dictionary object, be certain that the key you specify is valid or you encounter a KeyNotFoundException error:

try {
 //---KeyNotFoundException---
 Console.WriteLine(employees[1005].ToString());
} catch (KeyNotFoundException ex) {
 Console.WriteLine(ex.Message);
}

Rather than catching an exception when the specified key is not found, it's more efficient to use the TryGetValue() method:

string Emp_Name;
if (employees.TryGetValue(1005, out Emp_Name))
 Console.WriteLine(Emp_Name);
TryGetValue()
takes in a key for the Dictionary object as well as an out parameter that will contain the associated value for the specified key. If the key specified does not exist in the Dictionary object, the out parameter (Emp_Name, in this case) contains the default value for the specified type (string in this case, hence the default value is null).

When you use the foreach statement on a Dictionary object to iterate over all the elements in it, each Dictionary object element is retrieved as a KeyValuePair object:

foreach (KeyValuePair<int, string> Emp in employees)
 Console.WriteLine("{0} - {1}", Emp.Key, Emp.Value);

Here's the output from these statements:

1001 - Margaret Anderson
1002 - Howard Mark
1003 - John Smith
1004 - Brian Will

To get all the keys in a Dictionary object, use the KeyCollection class:

//---get all the employee IDs---
Dictionary<int, string>.KeyCollection
 EmployeeID = employees.Keys;
foreach (int ID in EmployeeID)
 Console.WriteLine(ID);

These statements print out all the keys in the Dictionary object:

1001
1002
1003
1004

If you want all the employees' names, you can use the ValueCollection class, like this:

//---get all the employee names---
Dictionary<int, string>.ValueCollection
 EmployeeNames = employees.Values;
foreach (string emp in EmployeeNames)
 Console.WriteLine(emp);

You can also copy all the values in a Dictionary object into an array using the ToArray() method:

//---extract all the values in the Dictionary object
// and copy into the array---
string[] Names = employees.Values.ToArray();
foreach (string n in Names)
 Console.WriteLine(n);

To remove a key from a Dictionary object, use the Remove() method, which takes the key to delete:

if (employees.ContainsKey(1006)) {
 employees.Remove(1006);
}

To sort the keys in a Dictionary object, use the SortedDictionary<K,V> class instead of the Dictionary<K,V> class:

SortedDictionary<int, string> employees =
 new SortedDictionary< int, string>();

Оглавление книги


Генерация: 0.572. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз