user3293835
user3293835

Reputation: 899

How to sort a list of string?

I have a list of persons 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.. How can I sort the list from older to younger?

calling people.Sort(x => x.Age); doesn't give the desired result. thanks.

Upvotes: 4

Views: 113

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101721

This should work (assuming that people is a List<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:

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:

people.Sort();

Upvotes: 6

Grant Winney
Grant Winney

Reputation: 66499

You can cast each string to an int, then order them, largest to smallest:

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

That should give you the desired result (assuming ages of "7", "22", and "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"

Upvotes: 6

Related Questions