HOWTO: Order generic collections with LINQ

To order collections in LINQ you can use the extension method OrderBy(), which can be found in the static class Sytem.Linq.Enumerable. It can be used in all types of collections that implement the interface System.Collections.Generic.IEnumerable. The following example orders a list of Person objects by their age.


List persons = new List();

persons.Add(new Person("Peggy", "Bundy", 39));
persons.Add(new Person("Doug", "Heffernan", 34));
persons.Add(new Person("Tim", "Tailor", 41));
persons.Add(new Person("Homer", "Simpson", 34));
persons.Add(new Person("Al", "Bundy", 41));

persons = persons.OrderBy(person => person.Age).ToList();

Output:
Heffernan, Doug (34)
Simpson, Homer (34)
Bundy, Peggy (39)
Tailor, Tim (41)
Bundy, Al (41)

The person class is quite simple:


public class Person
{
    public int Age { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }

    public override string ToString()
    {
        return string.Format("{0}, {1} ({2})", LastName, FirstName, Age);
    }
}



If you want to order the persons also by their last name you can use the extension method ThenBy(). It has to be appended at the end of the OrderBy() method.


persons = persons.OrderBy(person => person.Age).ThenBy(person => person.LastName).ToList();

Output:

Heffernan, Doug (34)
Simpson, Homer (34)
Bundy, Peggy (39)
Bundy, Al (41)
Tailor, Tim (41)


Kick It auf dotnet-kicks.de

Leave a Reply

Your email address will not be published.


*