3

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<Person> people = new List<Person>();
            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;
            }
        }
    }
}
cadsharp
  • 397
  • 2
  • 4
  • 15

2 Answers2

9

Try this:

List<Person> SortedList = people.OrderBy(o => o.Age).ToList();
Salah Akbari
  • 38,126
  • 10
  • 70
  • 102
8
people.Sort((p1, p2) =>
{
  return p1.Age - p2.Age;
});
manji
  • 46,486
  • 4
  • 90
  • 101
  • Linq already comes iwith that exact same code in OrderBy() – Scott Selby Aug 24 '15 at 21:07
  • [Are you sure?](http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,618) – manji Aug 24 '15 at 21:09
  • yea, i spoke too soon , I had thought initially you had a comparison . So you're right that it does not exist, but int already implements IComparable , so IMO just using built-in OrderBy is most "elegant way to accomplish this" – Scott Selby Aug 24 '15 at 21:35
  • 3
    OrderBy doesn't sort a list in-place. You can combine it with `.ToList()` to create a new sorted list, but it doesn't sort the original list, like this solution. – recursive Aug 24 '15 at 21:47
  • I don't really understand how it works but this was the only way I could get a list to sort on an Integer field. The .OrderBy didn't work for me on an integer value. – Caverman Feb 09 '19 at 00:54