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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With