Joan Venge
Joan Venge

Reputation: 331052

Sorting Winforms TreeView in a type safe way?

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

Upvotes: 1

Views: 607

Answers (2)

dlchambers
dlchambers

Reputation: 3752

One thing that tripped me up was that IComparer comes from System.Collections whereas IComparer comes from System.Collections.Generic.

I originally only had
using System.Collections.Generic;
and was getting a compile error:
Cannot implicitly convert type 'MyApp.NodeSorter' to 'System.Collections.IComparer'. An explicit conversion exists (are you missing a cast?)

The solution was to add
using System.Collections;

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062855

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);
    }
}

Upvotes: 2

Related Questions