public static IComparer<Employee> SalarySorter {

  get { return new SalaryComparer(); }

 }

 public string FirstName { get; set; }

 public string LastName { get; set; }

 public int Salary { get; set; }

 public override string ToString() {

  return FirstName + ', ' + LastName + ' $' + Salary;

 }

 public int CompareTo(Employee emp) {

  return this.FirstName.CompareTo(emp.FirstName);

 }

}

You can now sort the Employee objects using the default, or specify the SalarySorter property:

employees.Sort(); //---sort using FirstName (default)---

employees.Sort(Employee.SalarySorter); //---sort using Salary---

To allow the Employee objects to be sorted using the LastName property, you could define another class (say LastNameComparer) that implements the IComparer<T> interface and then declare the SalarySorter static property, like this:

public class Employee : IComparable<Employee> {

 private class SalaryComparer : IComparer<Employee> {

  public int Compare(Employee e1, Employee e2) {

   if (e1.Salary < e2.Salary) return -1;

   else if (e1.Salary == e2.Salary) return 0;

   else return 1;

  }

 }

 private class LastNameComparer : IComparer<Employee> {

  public int Compare(Employee e1, Employee e2) {

   return e1.LastName.CompareTo(e2.LastName);

  }

 }

 public static IComparer<Employee> SalarySorter {

  get { return new SalaryComparer(); }

 }

 public static IComparer<Employee> LastNameSorter {

  get { return new LastNameComparer(); }

 }

 public string FirstName { get; set; }

 public string LastName { get; set; }

 public int Salary { get; set; }

 public override string ToString() {

  return FirstName + ', ' + LastName + ' $' + Salary;

 }

 public int CompareTo(Employee emp) {

  return this.FirstName.CompareTo(emp.FirstName);

 }

}

You can now sort by LastName using the LastNameSorter property:

employees.Sort(Employee.LastNameSorter); //---sort using LastName---

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

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату