我怎么排序的自定义类的数组? [英] How do I sort an array of custom classes?
本文介绍了我怎么排序的自定义类的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一类与2串和1张(金额)。
I have a class with 2 strings and 1 double (amount).
类捐赠者
- 字符串名称
- 字符串注释
- 双击金额
现在我有捐赠者填补了一个数组。
我怎么能按金额排序?
Now I have a Array of Donators filled.
How I can sort by Amount?
推荐答案
如果您实施<一个href="http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx"><$c$c>IComparable<Donator>$c$c>你可以做到这一点是这样的:
If you implement IComparable<Donator>
You can do it like this:
public class Donator :IComparable<Donator>
{
public string name { get; set; }
public string comment { get; set; }
public double amount { get; set; }
public int CompareTo(Donator other)
{
return amount.CompareTo(other.amount);
}
}
您可以调用排序在任何你想要的,说:
You can then call sort on whatever you want, say:
var donors = new List<Donator>();
//add donors
donors.Sort();
在 .Sort()
要求你实现排序的的CompareTo()
方法。
The .Sort()
calls the CompareTo()
method you implemented for sorting.
还有没有拉姆达替代 IComparable的&LT; T&GT;
:
var donors = new List<Donator>();
//add donors
donors.Sort((a, b) => a.amount.CompareTo(b.amount));
这篇关于我怎么排序的自定义类的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文