我有一份人员名单 List<person>
public class Person
{
public string Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
他们的年龄可悲,string但实际上是类型,int并且具有类似的价值"45", "70", "1" etc..如何从旧到年轻的列表排序?
呼叫people.Sort(x => x.Age);不会产生预期的结果.谢谢.
这应该工作(假设people是a List<Person>):
people = people.OrderByDescending(x => int.Parse(x.Age)).ToList();
Run Code Online (Sandbox Code Playgroud)
如果您不想创建新的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));
}
}
Run Code Online (Sandbox Code Playgroud)
那你只需要使用Sort方法:
people.Sort();
Run Code Online (Sandbox Code Playgroud)
您可以将每个字符串转换为int,然后对它们进行排序,从最大到最小:
var oldestToYoungest = persons.OrderByDescending(x => Int32.Parse(x.Age));
Run Code Online (Sandbox Code Playgroud)
这应该给你想要的结果(假设年龄为"7","22"和"105"):
105
22
7
Run Code Online (Sandbox Code Playgroud)
如果您将它们排序为字符串,则无法获得所需的结果,如您所发现的那样.你最终会按字母顺序排列一个列表,例如:
"7"
"22"
"105"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |