Friday 3 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...