SortedList question

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
 
C

Chris R. Timmons

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.
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top