使用CompareTo以排序的前20种方式显示和未排序列表

时间:2013-11-21 13:41:37

标签: c# list sorting

我想在列表d中显示前20个项目。我在这里有一个实现:Displaying unsorted List's top 20 items

现在我想使用List类中的Sort()和CompareTo()内置方法来实现,而不是使用冒泡排序。即使在MSDN上阅读了一个例子,我也不确定如何使用CompareTo()和Sort()方法。

问题摘要:

我有一个未排序的列表

class WordCount
{
string word;
int count;
}

现在我必须按照计数的降序显示前20项。 如何使用Sort()或CompareTo()方法执行此操作?我对语法或如何使用Sort()感到困惑,您需要一个defaule比较器(究竟是什么?)和CompareTo()必须为它编写奇怪的代码....总的来说,我只是对如何使用Sort()和CompareTo()进行排序感到困惑。

1 个答案:

答案 0 :(得分:1)

var top20 = list.OrderByDescending(x=>x.count).Take(20).ToList();

您可能需要其他类似的结果:

var top20 = list.Take(20).OrderByDescending(x=>x.count).ToList();

如果后者是你想要的,你应该去做。因为你只需要20个第一项。使用Sort方法会对整个列表进行排序,您还必须使用Take,或直接在for(int i = 0; i < 20; i++) ...

中使用它

更新

使用SortIComparer

public class DescendingComparer : IComparer<WordCount> {
  public int Compare(WordCount x, WordCount y) {
    return -Comparer<int>.Default.Compare(x.count, y.count);
  }
}

现在你可以像这样使用Sort

list.Sort(new DescendingComparer());
//you should use the `Take(20)` to get the top or use a for like this:
for(int i = 0; i < 20; i++){
  //list[i]...
}