Monday, 5 February 2007

Generics, ICompare, and Delgates, and Anonymous methods to boot!

A colleague had an issues recently with map point. He was adding the waypoints to a route, but the ordering kept getting messed up.

He solved the problem by implementing ICompare. Very neat!

I have just finished reading the second chapter of the excellent Professional .net framework 2.0 by Joe Duffy covering Generics, Anonymous methods and Delegates among other things. This got me thinking if I could implements a generic ICompare to allow you to sort items the way you want quickly, and on the fly.

The first thing I had to do was create a function to add random items to a list of stringso I implement this function:-
private List<string> GenerateRandomItems(int iNumberToGenerate)
which does what it says on the tin.

I then created an object which is basically designed to wrap a generic object up, and using a delegate to a method it gets an object which implements ICompare
public class CustomSortExtender<TValueIn, TValueToCompare> : IComparable<CustomSortExtender<TValueIn, TValueToCompare>> where TValueToCompare : IComparable
{
public delegate TValueToCompare GetValueToCompareDelegate(TValueIn oValue);
private TValueIn m_oToExtend;
private TValueToCompare m_oValueToCompare;
public TValueToCompare ValueToCompare
{
get
{
return m_oValueToCompare;
}
}
private GetValueToCompareDelegate m_oCompareDelegate;
public CustomSortExtender(TValueIn oToExtend, GetValueToCompareDelegate oDelegate)
{
m_oToExtend = oToExtend;
m_oValueToCompare = oDelegate(oToExtend);
m_oCompareDelegate = oDelegate;
}
public override string ToString()
{
return m_oToExtend.ToString();
}
public int CompareTo(CustomSortExtender<TValueIn, TValueToCompare> oToCompare)
{
return m_oValueToCompare.CompareTo(oToCompare.ValueToCompare);
}
}
Now all I need to do is to wrap my original object (a string), create an anonymous method to extract what I want to sort by, and call List.Sort()!
List<string> oItems = GenerateRandomItems(40);
List<CustomSortExtender<string, string>> oSortedList = new List<CustomSortExtender<string, string>>();
foreach (string strWord in oItems)
{
oSortedList.Add(new CustomSortExtender<string, string>(strWord, delegate(string strIn) { return strIn.Substring(6, 1); }));
}
oSortedList.Sort();
listBox1.Items.AddRange(oSortedList.ToArray());
Then going forward if I ever want to change the way I sort I just need to change the function in the delegate!

Probably wouldn't recommend actually using this code to do what I have shown, it was more just a play with some of the cooler stuff in .net!

Expect a follow up blog explaining what each of the cooler parts mentioned do (Generics, ICompare, Delgates, Anonymous Methods).

No comments: