views:

93

answers:

1

Is it possible to sort a TreeView collection using IComparer<T> and not IComparer? After all they are all TreeNode values, right?

+2  A: 

If you mean via TreeViewNodeSorter, then it must be an IComparer (in short, it pre-dates generics). You could write something that shims this, but it probably isn't worth the trouble...

public static class ComparerWrapper
{ // extension method, so you can call someComparer.AsBasicComparer()
    public static IComparer AsBasicComparer<T>(this IComparer<T> comparer)
    {
        return comparer as IComparer
            ?? new ComparerWrapper<T>(comparer);
    }
}
sealed class ComparerWrapper<T> : IComparer
{
    private readonly IComparer<T> inner;
    public ComparerWrapper(IComparer<T> inner)
    {
        if (inner == null) throw new ArgumentNullException("inner");
        this.inner = inner;
    }
    int IComparer.Compare(object x, object y)
    {
        return inner.Compare((T)x, (T)y);
    }
}
Marc Gravell
Thanks Marc. Is it at least possible to have a custom Sort method to sort them. I guess that's not possible due to the TreeView controller.
Joan Venge
By that I mean a custom sort that I can call that will not cast things from object to TreeNode.
Joan Venge