How to sort a list of strings?

I have a list of faces List<person>

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

their age is sorrily in string, but has type value intand has values ​​such as "45", "70", "1" etc.. How can I sort the list from older to younger?

the call people.Sort(x => x.Age);does not give the desired result. thanks.

+4
source share
2 answers

You can attribute each line to int, and then arrange it as much as possible:

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

This should give you the desired result (assuming the age is "7", "22" and "105"):

105
22
7

If you sort them as strings, you will not get the desired result, as you know. You will get a list sorted alphabetically, for example:

"7"
"22"
"105"
+6

( , 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();
+6

Source: https://habr.com/ru/post/1529512/


All Articles