Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of string?

Tags:

c#

sorting

linq

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.

like image 572
user3293835 Avatar asked Dec 16 '22 01:12

user3293835


1 Answers

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"
like image 176
Grant Winney Avatar answered Jan 08 '23 02:01

Grant Winney