How to sort object array by specific property in C#?


Here, you will learn how to sort an array of objects by specific property in C#.

There are two ways you can sort an object array by a specific property, using Array.Sort() method and by using LINQ query.

class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
 
Person[] people = {
        new Person(){ FirstName="Steve", LastName="Jobs"},
        new Person(){ FirstName="Bill", LastName="Gates"},
        new Person(){ FirstName="Lary", LastName="Page"}
    };

The people array in the above example contains objects of Person class. You cannot use Array.Sort(people) because array contains objects, not primitive values.

Now, let's sort the above people array by the LastName property. For that, you need to create a class and implement IComparer interface, as shown below.

Example: Custom Comparer Class
class PersonComparer : IComparer
{
    public int Compare(object x, object y)
    {
        return (new CaseInsensitiveComparer()).Compare(((Person)x).LastName, ((Person)y).LastName);
    }
}

Now, we can sort an array using Array.Sort() method by specifying IComparer class.

Example: Sort Object Array
Person[] people = {
    new Person(){ FirstName="Steve", LastName="Jobs"},
    new Person(){ FirstName="Bill", LastName="Gates"},
    new Person(){ FirstName="Lary", LastName="Page"}
};
 
Array.Sort(people, new PersonComparer());

The same result can be achieved using LINQ query easily, as shown below.

Example: Sort using LINQ
Person[] people = {
    new Person(){ FirstName="Steve", LastName="Jobs"},
    new Person(){ FirstName="Bill", LastName="Gates"},
    new Person(){ FirstName="Lary", LastName="Page"}
};

var qry = from p in list
        orderby p.LastName
        select p;
 
Array.ForEach<Person>(qry.ToArray<Person>(), p => Console.WriteLine(p.FirstName + " " + p.LastName));