【问题标题】:C# IComparer custom sort list using child count with different conditionC# IComparer 自定义排序列表使用不同条件的子计数
【发布时间】:2016-06-20 11:29:24
【问题描述】:

我想使用自定义比较器对 C# 列表进行排序。 我有 TreeNodes 列表,我想使用子节点数对它们进行排序 (TreeNode.GetNodeCount(true)),但是节点数

我当前的代码是:

public class XPathComparer : IComparer<TreeNode>
{
    public int Compare(TreeNode x, TreeNode y)
    {
        if ( 
            (x != null && x.GetNodeCount(true) <= 2) || 
            (y != null && y.GetNodeCount(true) <= 2) 
            )
            return -1;
        return x.GetNodeCount(true).CompareTo(y.GetNodeCount(true));
    }
}

【问题讨论】:

    标签: c# list sorting compare


    【解决方案1】:

    虽然你没有提供调用堆栈或异常,但我怀疑你得到了Arg_BogusIComparerArgumentException

    <data name="Arg_BogusIComparer" xml:space="preserve">
        <value>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</value>
    </data>
    

    当您的比较器没有为元素提供一致的结果时,将引发此异常。在您的示例中,x 小于 yy 同时小于 x 如果它们都有 1 个孩子。

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 2020-03-24
      • 2020-09-14
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多