Is it possible to sort a TreeView
collection using IComparer<T>
and not IComparer
? After all they are all TreeNode
values, right?
views:
93answers:
1
+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
2010-03-19 18:51:41
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
2010-03-19 19:29:35
By that I mean a custom sort that I can call that will not cast things from object to TreeNode.
Joan Venge
2010-03-19 19:31:48