Friday, August 3, 2018

c# - How to sort class list by integer property?





Below I have created a list with 4 elements of type Person. I would like to sort the Person list in ascending order according to the Age property. Is there an elegant way to accomplish this with LINQ or IComparable (or something else) so I don't have to write my own algorithm from scratch?



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program

{
static void Main(string[] args)
{
List people = new List();
people.Add(new Person("Matthew", 27));
people.Add(new Person("Mark", 19));
people.Add(new Person("Luke", 30));
people.Add(new Person("John", 20));

// How to sort list by age?


}

private class Person
{
string Name { get; set; }
int Age { get; set; }

public Person(string name, int age)
{

Name = name;
Age = age;
}
}
}
}

Answer



Try this:




List SortedList = people.OrderBy(o=>o.Age).ToList();

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...