So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.
Turns out the IList
This question inspired me to write a blog post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/
I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList
public static class SortExtensions
{
// Sorts an IList in place.
public static void Sort(this IList list, Comparison comparison)
{
ArrayList.Adapter((IList)list).Sort(new ComparisonComparer(comparison));
}
// Sorts in IList in place, when T is IComparable
public static void Sort(this IList list) where T: IComparable
{
Comparison comparison = (l, r) => l.CompareTo(r);
Sort(list, comparison);
}
// Convenience method on IEnumerable to allow passing of a
// Comparison delegate to the OrderBy method.
public static IEnumerable OrderBy(this IEnumerable list, Comparison comparison)
{
return list.OrderBy(t => t, new ComparisonComparer(comparison));
}
}
// Wraps a generic Comparison delegate in an IComparer to make it easy
// to use a lambda expression for methods that take an IComparer or IComparer
public class ComparisonComparer : IComparer, IComparer
{
private readonly Comparison _comparison;
public ComparisonComparer(Comparison comparison)
{
_comparison = comparison;
}
public int Compare(T x, T y)
{
return _comparison(x, y);
}
public int Compare(object o1, object o2)
{
return _comparison((T)o1, (T)o2);
}
}
With these extensions, sort your IList just like you would a List:
IList iList = new []
{
"Carlton", "Alison", "Bob", "Eric", "David"
};
// Use the custom extensions:
// Sort in-place, by string length
iList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));
// Or use OrderBy()
IEnumerable ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));
There's more info in the post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/