我有一个人员列表 List<person>
public class Person
{
public string Age { get; set; }
}
他们的年龄是用 string
表示的,但实际上是属于 int
类型的,取值如"45", "70", "1" 等
。如何把这个列表按从大到小的顺序排序?
调用 people.Sort(x => x.Age);
不能得到想要的结果。谢谢。
people
是一个List<Person>
):people = people.OrderByDescending(x => int.Parse(x.Age)).ToList();
如果您不想创建一个新的List
,您可以为您的类实现IComparable<T>
接口:
public class Person : IComparable<Person>
{
public string Age { get; set; }
public int CompareTo(Person other)
{
return int.Parse(other.Age).CompareTo(int.Parse(this.Age));
}
}
Sort
方法:people.Sort();
var oldestToYoungest = persons.OrderByDescending(x => Int32.Parse(x.Age));
假设年龄是"7"、"22"和"105",那么这将给你所期望的结果:
105
22
7
"7"
"22"
"105"