ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button
  Implementing Custom Data Bindable Classes: CollectionBase
Subject:   Implementing sort for multiple properties
Date:   2005-01-12 15:30:47
From:   Daniel_Odulo
Response to: Using objects with more than 1 property

No you don't. The example below in in VB, you'll have to convert to C# yourself, sorry. But it's all straight forward.

Public Enum SortOrder
ID = 1
Code = 2
Description = 3
Price = 4
End Enum

Public Enum SortDirection
Ascending = 1
Descending = 2
End Enum

Public Sub Sort(ByVal SortOrder As SortOrder, ByVal SortDirection As SortDirection)
Dim Sorter As IComparer = New AscendingSorter(SortOrder, SortDirection)
End Sub

Private Class AscendingSorter
Implements IComparer

Private _SortOrder As SortOrder
Private _SortDirection As SortDirection

Public Sub New(ByVal SortOrder As SortOrder, ByVal SortDirection As SortDirection)
_SortOrder = SortOrder
_SortDirection = SortDirection
End Sub

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
Dim p1 As Product = CType(x, Product)
Dim p2 As Product = CType(y, Product)

Dim ic1 As IComparable, ic2 As IComparable

Select Case _SortOrder
Case SortOrder.Code
ic1 = CType(p1.Code, IComparable)
ic2 = CType(p2.Code, IComparable)
Case SortOrder.Description
ic1 = CType(p1.Description, IComparable)
ic2 = CType(p2.Description, IComparable)
Case SortOrder.ID
ic1 = CType(p1.ID, IComparable)
ic2 = CType(p2.ID, IComparable)
Case SortOrder.Price
ic1 = CType(p1.Price, IComparable)
ic2 = CType(p2.Price, IComparable)
End Select

If _SortDirection = SortDirection.Ascending Then
Return ic1.CompareTo(ic2)
Return ic2.CompareTo(ic1)
End If
End Function
End Class

Daniel Odulo


* Full Service Hosted E-Commerce Solution
* Custom Data-Driven Solutions
Desktop Applications / Web Applications / Web Enabling Data
MS Access / MS SQL Server / ASP / VBScript / VBA / .NET

I am located in: San Jose, California, USA