简体   繁体   English

如何排序字符串列表?

[英]How to sort a list of string?

I have a list of persons List<person> 我列出了人员List<person>

public class Person
{
    public string Age { get; set; }
}

their age sorrily is in string but is infact of type int and has values like "45", "70", "1" etc. . 他们的年龄天生就是string但实际上是int类型,其值为"45", "70", "1" etc. How can I sort the list from older to younger? 如何从旧到年轻的列表排序?

calling people.Sort(x => x.Age); 呼叫people.Sort(x => x.Age); doesn't give the desired result. 没有给出理想的结果。 thanks. 谢谢。

This should work (assuming that people is a List<Person> ) : 这应该工作(假设peopleList<Person> ):

people = people.OrderByDescending(x => int.Parse(x.Age)).ToList();

If you don't want to create a new List , alternatively you can implement IComparable<T> for your class: 如果您不想创建新的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));
    }
}

Then you just need to use Sort method: 然后你只需要使用Sort方法:

people.Sort();

You can cast each string to an int, then order them, largest to smallest: 您可以将每个字符串转换为int,然后对它们进行排序,从最大到最小:

var oldestToYoungest = persons.OrderByDescending(x => Int32.Parse(x.Age));

That should give you the desired result (assuming ages of "7", "22", and "105"): 这应该给你想要的结果(假设年龄为“7”,“22”和“105”):

105
22
7

If you sort them as strings, you won't get the desired result, as you found out. 如果您将它们排序为字符串,则无法获得所需的结果,如您所发现的那样。 You'll end up with a list ordered alphabetically, like: 你最终会按字母顺序排列一个列表,例如:

"7"
"22"
"105"

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

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