Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
136
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

THE IENUMERATOR AND ICOMPARER INTERFACES 519

As you can see, it’s straightforward to write your own custom comparers and sort your custom object in any way that suits your application. Custom comparisons may include more complicated calculations, not just comparisons. For example, you can sort Rectangles by their area, color values by their hue or saturation, and customers by the frequency of their orders.

The example of this section is called CustomComparer; you can find it in this chapter’s folder on the CD. The main form (Figure 11.5) contains a single button, which populates the collection and then prints the original collection, the collection sorted by name, and then the collection sorted by birth date.

Figure 11.5

The CustomCompare project: how to sort collections of objects according to any property

Custom Sorting of a SortedList

The items of a SortedList are sorted according to their keys. Of course, the SortedList will not be able to maintain the order of the keys, unless the keys are of a base type, such as integers or strings. If you need to use objects as keys, you must simply provide a function to implement the IComparer interface, as you know well by now. In this section, we’ll build a custom comparer for the same SortedList we built earlier in the SortedList example. The custom comparer will sort the keys in the collection according to the cosine of their values. If you’re not interested in trigonometry and don’t know what the cosine of a number is, don’t worry. It’s a function that transforms a number into another number. If the keys were points in the space, you could sort them according to their distance from the sun, or whatever. The idea is that you can transform the keys into another meaningful value and sort the collection according to the transformed value.

Note Whether the SortedList is sorted according to its keys, or a transformation of the keys, these values must be unique. It’s not enough that the original keys be unique. Their transformations must be also unique.

Let’s start with the custom comparer, which comparers the cosines of the two values. Add a new class to the SortedList project and name it CustomComparer. Then enter the code from Listing 11.19 in its code window.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

520 Chapter 11 STORING DATA IN COLLECTIONS

Listing 11.19: A Custom Comparer for the SortedList

Class CustomComparer : Implements IComparer

Public Function Compare(ByVal o1 As Object, ByVal o2 As Object) As Integer _ Implements IComparer.Compare

Dim num1, num2 As Integer Try

num1 = CType(o1, Integer) num2 = CType(o2, Integer)

Catch compareException As system.Exception Throw (compareException)

Exit Function End Try

If Math.Cos(num1) < Math.Cos(num2) Then Return -1

Else

If Math.Cos(num1) > Math.Cos(num2) Then Return 1

Else Return 0

End If End If

End Function End Class

The Compare() function is very similar to the Compare() functions of the previous examples. Instead of comparing the arguments directly, it transforms them with the help of the Cos() function and then compares the transformed values. You can replace the Cos() function with a custom function that performs as many calculations as necessary.

To test the custom comparer, open the SortedList project, place another button on the form, and enter the following declaration in the new button’s Click event handler:

Dim sList As New System.Collections.SortedList(New CustomComparer())

This statement tells the SortedList to sort its keys using the CustomComparer, not the default comparer for the integer data type. Then copy the statements that populate the SortedList and paste them after the previous declaration. Finally, enter a few more statements to iterate through the SortedList and print the key–value pairs. Here’s the complete listing of the second button’s event handler for your reference:

Dim sList As New System.Collections.SortedList(New CustomComparer) ‘ Populate SortedList

sList.Add(16, “item 3”) sList.Add(10, “item 9”) sList.Add(15, “item 4”) sList.Add(17, “item 2”) sList.Add(11, “item 8”)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com