[英]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.一个小小的谷歌有很长的路要走。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.