| Article: |
Implementing Custom Data Bindable Classes: CollectionBase | |
| Subject: | Using objects with more than 1 property | |
| Date: | 2004-07-05 21:45:29 | |
| From: | dwfresh | |
|
This is a great article, however, if I had a products class with 10 properties, and wanted to allow a user to sort on any property, would I have to write 10 different 'AscendingNameSorter' type classes? ie: AscendingTypeSorter, AscendingManufacturerSorter, etc. private class AscendingNameSorter : IComparer { public int Compare(Object x, Object y) { Products.Product p1 = (Products.Product)x; IComparable ic1 = (IComparable)p1.Name;
|
||
Showing messages 1 through 2 of 2.
-
Using objects with more than 1 property
2004-09-13 16:09:47 jamesstill [Reply | View]
Doug, you do need to implement against IComparer for each sort property. Once that's done, I'd modify the Sort method accordingly:
public void Sort(SortType eType)
{
switch(eType)
{
case SortType.Name:
IComparer NameSorter = new _
AscendingNameSorter();
InnerList.Sort(NameSorter);
break;
// next case etc.
}
}
In this case, you'd have a public enum in the namespace defining the sort type options. Hope this helps.




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)
Me.InnerList.Sort(Sorter)
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)
Else
Return ic2.CompareTo(ic1)
End If
End Function
End Class
Daniel Odulo
-----------------------------------------------------------
http://www.Odulo.com/consulting
* 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
-----------------------------------------------------------