.NET Sorting: Compare Just About Any Property of Any Object, Page 2
Defining Something to Sort
You can sort just about anything. To make the demonstration reflect something you may be familiar with, Listing 3 contains an implementation of a simple Customer class:
Listing 3: A Simple Customer Class
Public Class Customer
Private FCustomerNumber As Integer
Private FName As String
Public Sub New(ByVal customerNumber As Integer, _
ByVal name As String)
FCustomerNumber = customerNumber
FName = name
End Sub
Public ReadOnly Property CustomerNumber() As Integer
Get
Return FCustomerNumber
End Get
End Property
Public Property Name() As String
Get
Return FName
End Get
Set(ByVal value As String)
FName = value
End Set
End Property
End Class
You can sort a list of Customer objects by the Name or CustomerNumber.
Invoking the Sort Behavior
Listing 4 demonstrates how to create a generic list of strongly typed Customer objects, add some Customers to the list, and sort the Customers by Name:
Listing 4: Code to Demonstrate the PropertyComparer
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Reflection
Module Module1
Sub Main()
Dim list As List(Of Customer) = New List(Of Customer)
list.Add(New Customer("Paul"))
list.Add(New Customer("Noah"))
list.Add(New Customer("Alex"))
list.Add(New Customer("Jim"))
list.Sort(New PropertyComparer(Of Customer)("Name"))
Dim o As Customer
For Each o In list
Console.WriteLine(o.Name)
Next
Console.ReadLine()
End Sub
End Module
If you changed the construction of the PropertyComparer to initialize the PropertyComparer with the CustomerNumber property name, you would get a completely different sort result.
A General Technique for Sorting Objects
Advanced techniques are the lever, fulcrum, and place to stand that can help you move mountains. This example combined reflection, interfaces, and generics to create a general technique for sorting objects based on any field.
I use a variation of the PropertyComparer in production, and it's a nice addition to the sorting behavior in .NET.
Acknowledgements
Special thanks to my very smart friend Chris Chartrand in Ontario for coming up with the directional variation of my original PropertyComparer class.
About the Author
Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his new book UML DeMystified from McGraw-Hill/Osborne. Paul is an architect for Tri-State Hospital Supply Corporation. You may contact him for technology questions at pkimmel@softconcepts.com.
If you are interested in joining or sponsoring a .NET Users Group, check out www.glugnet.org.
