"Johannes" <an*******@discussions.microsoft.com> wrote in
news:02****************************@phx.gbl:
I've read that the SortedList object can sort its elements
in alphabetical or numerical order. If this is correct,
how can I set the sort order to numerical.
Regardless of the key/value pairs I add to the list, it
only seems to sort alphabetically.
Johannes,
You can implement the IComparer interface to sort the keys in your
SortedList:
using System;
using System.Collections;
namespace Example
{
// An implementation of IComparer.
public class Int32ComparerClass : IComparer
{
public int Compare(object x, object y)
{
// This code assumes neither x and y are null,
// and they both can be successfully converted to Int32s.
return Convert.ToInt32(x) - Convert.ToInt32(y);
}
}
public class Test
{
[STAThread]
public static void Main()
{
SortedList numericList =
new SortedList(new Int32ComparerClass());
numericList.Add("10", "Ten");
numericList.Add("11", "Eleven");
numericList.Add("1", "One");
numericList.Add("2", "Two");
numericList.Add("3", "Three");
foreach (DictionaryEntry de in numericList)
Console.WriteLine(de.Key + ", " + de.Value);
}
}
}
Hope this helps.
Chris.
-------------
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/