简体   繁体   English

使用 List.Sort(Comparison) 在 C# 中对列表进行排序<T>比较

[英]Sorting a List in C# using List.Sort(Comparison<T> comparison

I have created a class as follows:我创建了一个类,如下所示:

public class StringMatch
{
   public int line_num;
   public int num_of_words;
}

I have created a list我创建了一个列表

List<StringMatch> sm;

it has few elements in it.它的元素很少。

How do I sort this list using the Comparison<T> comparison overload?如何使用Comparison<T>比较重载对这个列表进行排序? The sorting must be done based on the num_of_words field.必须根据num_of_words字段进行排序。

You can write lambda expression comparing two objects like this:您可以编写比较两个对象的 lambda 表达式,如下所示:

sm.Sort((x,y)=>x.num_of_words.CompareTo(y.num_of_words));

you can inverse sorting adding -你可以逆排序添加-

sm.Sort((x,y)=>-x.num_of_words.CompareTo(y.num_of_words));

您可以使用 Linq OrderBy方法 -

sm = sm.OrderBy(i => i.num_of_words).ToList();

There is a usage example on the official microsoft documentation . 微软官方文档上有一个用法示例。 The example uses strings.该示例使用字符串。 Replace with int for your use.替换为int供您使用。

private static int CompareDinosByLength(string x, string y)
{
   ...
}

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("");
dinosaurs.Add(null);
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Sort(CompareDinosByLength);

A little google goes a long way.一个小小的谷歌有很长的路要走。

Using Comparison is an older and more clunky way of sorting collections.使用Comparison是一种较旧且笨拙的集合排序方式。 My advice would be to use the OrderBy method found in Linq :我的建议是使用Linq 中OrderBy方法:

var orderedSm = sm.OrderBy(x => x.num_of_words).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM