IComparer没有按预期工作

时间:2015-02-18 21:54:52

标签: c# .net list sorting

我的程序的功能是计算文档中唯一单词的出现次数,然后按排序顺序显示它们。我首先遍历所有单词并将它们输入到字典中,然后在字典中增加它们遇到的次数。然后我将字典转换为列表并使用.Sort作为参数调用IComparer方法。这里的代码如下所示:

List<KeyValuePair<string,long>> wordList = wordCount.ToList();
IComparer<KeyValuePair<string,long>> comparison = new comparator();
wordList.Sort(comparison);

我正在使用的IComparer类

public class comparator : IComparer<KeyValuePair<string, long>>
{
    public int Compare(KeyValuePair<string, long> x, KeyValuePair<string, long> y)
    {
        if (x.Value > y.Value)
            return 1;
        else
            return 0;
    }
}

但是,当我完成排序时,列表不会按照我希望的那样按KeyValuePair的值排序。我在这里做错了什么?

screen shot of poor sorting order

2 个答案:

答案 0 :(得分:7)

在比较器实现中y.Value大于x.Value时,您错过了这种情况:

public class comparator : IComparer<KeyValuePair<string, long>>
{
    public int Compare(KeyValuePair<string, long> x, KeyValuePair<string, long> y)
    {
        if (x.Value > y.Value)
        {
            return 1;
        }
        else if (x.Value < y.Value)
        {
            return -1;
        }
        else
            return 0;
    }
}

public class comparator : IComparer<KeyValuePair<string, long>>
{
    public int Compare(KeyValuePair<string, long> x, KeyValuePair<string, long> y)
    {
        return x.Value.CompareTo(y.Value);
    }
}

您也可以使用LINQ OrderBy代替Sort。它更容易使用,因为它需要一个lambda表达式,但它会创建一个新的集合,而不是对提供的集合进行排序。

var sorted = wordList.OrderByDescending(x => x.Value).ToList();

您可以在一个查询中执行所有处理(假设words是包含所有单词的字符串的集合):

var sortedWithCount = words.GroupBy(x => x)
                           .OrderByDescending(g => g.Count)
                           .ToList(g => new { Word = g.Key, Count = g.Count });

答案 1 :(得分:1)

实际上,作为Compare方法的结果,您应该返回10-1。但在您的情况下,您可以使用CompareTo类型的long方法获取示例:

public class Comparator : IComparer<KeyValuePair<string, long>>
{
    public int Compare(KeyValuePair<string, long> x, KeyValuePair<string, long> y)
    {
        return x.Value.CompareTo(y.Value);
    }
}

作为一个好的实践,请将您的课程重命名为Comparator,而不是comparator。保持干净的代码!