Monday, April 27, 2009

C# - How to have a reverse ordered Generic SortedList collection


The folowing code sample creates a generic SortedList using DateTimes as the keys and integers as the values.. The normal behavior of a generic SortedList collection is to sort the added items in ascending order but this example use generic IComparer to sort it in reverse order and the sample code show how to loop through the SortedList members (It's possible to loop by index too).

A System.Collections.Generic.IComparer to sort based on DateTime in reverse order:

...
using System.Collections;
using System.Collections.Generic;
...

public class DecendingDateCompare : IComparer
{
public int Compare(DateTime x, DateTime y)
{
return x.CompareTo(y) * -1;
}
}


A sample code to test:

...
using System.Collections;
using System.Collections.Generic;
...
SortedList aSortedList =
new SortedList(new DecendingDateCompare());

aSortedList.Add(DateTime.Now.AddDays(-10), 100);
aSortedList.Add(DateTime.Now.AddDays(10), 10);
aSortedList.Add(DateTime.Now.AddDays(-5), 90);
aSortedList.Add(DateTime.Now.AddDays(5), 20);
aSortedList.Add(DateTime.Now.AddDays(-3), 80);
aSortedList.Add(DateTime.Now.AddDays(3), 30);

StringBuilder sb = new StringBuilder();
IDictionaryEnumerator iDicEnum =
(IDictionaryEnumerator) aSortedList.GetEnumerator();

while( iDicEnum.MoveNext() )
sb.AppendLine( iDicEnum.Key.ToString() +
", " +
iDicEnum.Value.ToString() );

MessageBox.Show(sb.ToString());

Share/Bookmark

No comments: