To print out all the elements contained within a SpamPhraseList object, you can use the same statements that you used in the previous section:

SpamPhraseList list = new SpamPhraseList();

foreach (string s in list) //---error---

 Console.WriteLine(s);

Behind the scenes, the compiler is generating the following code for the foreach statement:

SpamPhraseList list = new SpamPhraseList();

IEnumerator<string> s = list.GetEnumerator();

while (s.MoveNext())

 Console.WriteLine((string)s.Current);

Implementing Comparison Using IComparer<T> and IComparable<T>

One of the tasks you often need to perform on a collection of objects is sorting. You need to know the order of the objects so that you can sort them accordingly. Objects that can be compared implement the IComparable interface (the generic equivalent of this interface is IComparable<T>). Consider the following example:

string[] Names = new string[] {

 'John', 'Howard', 'Margaret', 'Brian'

};

foreach (string n in Names)

 Console.WriteLine(n);

Here, Names is a string array containing four strings. This code prints out the following:

John

Howard

Margaret

Brian

You can sort the Names array using the Sort() method from the abstract static class Array, like this:

Array.Sort(Names);

foreach (string n in Names)

 Console.WriteLine(n);

Now the output is a sorted array of names:

Brian

Howard

John

Margaret

In this case, the reason the array of string can be sorted is because the String type itself implements the IComparable interface, so the Sort() method knows how to sort the array correctly. The same applies to other types such as int, single, float, and so on.

What if you have your own type and you want it to be sortable? Suppose that you have the Employee class defined as follows:

public class Employee {

 public string FirstName { get; set; }

 public string LastName { get; set; }

 public int Salary { get; set; }

 public override string ToString() {

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

 }

}

You can add several Employee objects to a List object, like this:

List<Employee> employees = new List<Employee>();

employees.Add(new Employee() {

 FirstName = 'John',

 LastName = 'Smith',

 Salary = 4000

});

employees.Add(new Employee() {

 FirstName = 'Howard',

 LastName = 'Mark',

 Salary = 1500

});

employees.Add(new Employee() {

 FirstName = 'Margaret',

 LastName = 'Anderson',

 Salary = 3000

});

employees.Add(new Employee() {

 FirstName = 'Brian',

 LastName = 'Will',

 Salary = 3000

});

To sort a List object containing your Employee objects, you can use the following:

employees.Sort();

However, this statement results in a runtime error (see Figure 13-4) because the Sort() method does not know how Employee objects should be sorted.

Figure 13-4

To solve this problem, the Employee class needs to implement the IComparable<T> interface and then implement the CompareTo() method:

public class Employee : IComparable<Employee> {

 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);

 }

}

The CompareTo() method takes an Employee parameter, and you compare the current instance (represented by this) of the Employee class's

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

0

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

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