Skip to content
Related Articles

Related Articles

How to Sort Object Array By Specific Property in C#?

Improve Article
Save Article
Like Article
  • Last Updated : 15 Feb, 2022

Sorting basically means arranging a given set of elements in a specific order. There are two orders in which we can sort the given set of elements that is either in ascending order or descending order. For example, we have a set that [2, 3, 16, 10], now we can sort this set of elements in ascending order that is [2, 3, 10, 16] or we can sort this set of elements in descending order that is [16, 10, 3, 2] according to our requirement. In C#, we can sort the object array by specific property using the following ways:

  • Array.sort()
  • LINQ query

Array.sort() Method

Array.sort() method is used to sort elements of an array. There is a total of 17 overloaded versions of this method are available out of which we can use the below method to sort an object array by a specific property. 

Syntax:

Sort(array, IComparer) Method

Here, array represents an array that has to be sorted and IComparer is a generic interface.

Exceptions: It will throw the following exceptions:

  • ArgumentNullException: When the passed array is null.
  • InvalidOperationException: If one or more elements in the array do not follow the IComparable<T> generic interface.

Example: In this program, elements of the array students are of Student type. They have been sorted according to the LastName of each student. The logic is implemented in Compare() method of the StudentComparer class method.

C#




// C# program to sort object array by specific property 
using System;
using System.Collections;
  
class GFG{
  
// Comparator class
// to sort according to last name
class StudentComparer : IComparer
{
    public int Compare(object x, object y)
    {
        return(new CaseInsensitiveComparer()).Compare(((Student)x).LastName,
               ((Student)y).LastName);
    }
}
  
// Student class
class Student 
{
    public int Id
    {
        get;
        set;
    }
    public string FirstName
    {
        get;
        set;
    }
    public string LastName
    {
        get;
        set;
    }
}
  
// Driver code
static public void Main()
{
      
    // Initializing an array of Student type
    Student[] students = {
             
            // Initializing using constructors
            new Student(){ FirstName = "Bhuwanesh",
                           LastName = "Nainwal" },
            new Student(){ FirstName = "Anil",
                           LastName = "Thapa" },
            new Student(){ FirstName = "Hitesh",
                           LastName = "Kumar"
    };
        
      // Calling sort method by passing comparator
      // function as an argument
     Array.Sort(students, new StudentComparer());
        
      // Print array elements
    foreach(var item in students)
    {
        Console.WriteLine(item.FirstName + ' '
                          item.LastName);
    }
}
}
Output
Hitesh Kumar
Bhuwanesh Nainwal
Anil Thapa

Using LINQ query

We can also sort the object array using the LINQ queries. The LINQ query syntax begins with from keyword and ends with the Selector GroupBy keyword. After using from the keyword you can use different types of standard query operations like filtering, grouping, etc. according to your need in the query.

Approach:

1. Firstly we need to add System.Linq namespace in the code.

using System.Linq;

2. Then, we need to make a collection of elements or data sources on which we will perform operations. For example:

List list = new List(){
    {"FirstName1", "LastName1"},
    {"FirstName2", "LastName2"},
    {"FirstName3", "LastName3"},
    {"FirstName4", "LastName4"}
};

Here, each element is of type student and have the following data members: FirstName and LastName

3. Then, we will create the query by using the query keywords like orderby, select, etc. For example:

var qry = from s in list
          orderby s.FirstName/LastName
          select s;

Here qry is the query variable that will store the result of the query expression. The from clause is used to specify the data source, i.e, list, orderby clause will arrange them into the specified order and select clause provides the type of the returned items. 

4. The last step is to execute the query by using a foreach loop. For example:

Array.ForEach<Student>(qry.ToArray<Student>(), 
                       s => Console.WriteLine(s.FirstName + " " + 
                                              s.LastName));

Example: In this program, we have sorted the given array of elements (of Student type) according to the LastName property.

C#




// C# program to sort object array by specific property 
using System;
using System.Collections;
  
class GFG{
  
// Comparator class
// to sort according to last name
class StudentComparer : IComparer
{
    public int Compare(object x, object y)
    {
        return(new CaseInsensitiveComparer()).Compare(((Student)x).LastName,
               ((Student)y).LastName);
    }
}
  
// Student class
class Student 
{
    public int Id
    {
        get;
        set;
    }
    public string FirstName
    {
        get;
        set;
    }
    public string LastName
    {
        get;
        set;
    }
}
  
// Driver code
static public void Main()
{
      
    // Initializing an array of Student type
    Student[] students = {
             
            // Initializing using constructors
            new Student(){ FirstName = "Bhuwanesh",
                           LastName = "Nainwal" },
            new Student(){ FirstName = "Anil",
                           LastName = "Thapa" },
            new Student(){ FirstName = "Hitesh",
                           LastName = "Kumar"
    };
        
      // Calling sort method by passing comparator
      // function as an argument
     Array.Sort(students, new StudentComparer());
        
      // Print array elements
    foreach(var item in students)
    {
        Console.WriteLine(item.FirstName + ' '
                          item.LastName);
    }
}
}
Output
Hitesh Kumar
Bhuwaneh Nainwal
Anil Thapa

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!