SortedList question

  • Thread starter Thread starter Johannes
  • Start date Start date
J

Johannes

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.

Thanks
 
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.
 
Johannes said:
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.

Give the SortedList constructor an appropriate IComparer which compares
objects in the way you want them sorted, and it can sort them any way
you want.
 
Back
Top