How To Sort Object Array By Specific Property In C#

In this article, we will discuss how to Sort an Object Array by a Specific Property . Sorting objects within arrays is a frequent operation, particularly in situations where we need to handle complex data structures. In C#, we can sort array objects by virtue of a particular property. For instance, we can sort an employee list by their salaries or order a product collection by their prices.

Sorting is a process of putting sequenced elements in definite order. Sorting can be done in two ways either like the elements in increasing order or the decreasing order. Take, for instance, [1,13,16,10] as an example; we might choose to either sort this in ascending order [1,10,13,16] or descending order that is [16,13,10,1] according to the requirement. In C#, we can sort the object array by specific property using the following ways:

  • Array.sort
  • LINQ query
  • What is the Array.sort method?

The array.sort method is applied to sort elements of the array. The method with 17 overload versions is available, among which we can choose one method to sort the objects based on a certain property.

In this case, Array denotes an array to be sorted.

Exceptions: It will show the following exceptions:

Whenever people travel into space, it can be challenging to adapt to the environment.

ArgumentNullException: For null array object reference, the given code will say (Passed Array is null).

InvalidOperationException: So, the problem is if one or more array elements are incompatible with the IComparable class.

Example: This program requires elements in the array student to be of Student but type. They are grouped together by the tag "_LName" of each student. The logic is implemented as a method of the StudentComparer class using the Compare method.

Example:

Let us take a program to implement how to Sort-Object Array by Specific Property in C#.

Example

using System; 
using System.Collections; 
class SortObject{ 
//Sort the list according to the name
class StudentComparator : IComparer 
{ 
    public int Compare(object x, object y) 
    { 
        return(new CaseInsensitiveComparer()).Compare(((StudentsDetails)x).La_Name,((StudentsDetails)y).La_Name); 
    } 
} 
// StudentDetails class 
class StudentsDetails 
{ 
	public int IdName 
	{ 
		get; 
		set; 
	} 
	public string Fir_Name 
	{ 
		get; 
		set; 
	} 
	public string La_Name 
	{ 
		get; 
		set; 
	} 
} 
// Driver code 
static public void Main() 
{ 
	// Initialization of an array of Student type 
	// the array initialisation of student type
	StudentsDetails[] stud = { 
			// the constructor's initialisation
			new StudentsDetails(){ Fir_Name = "Somesh", 
						La_Name = "Jaiswal" }, 
			new StudentsDetails(){ Fir_Name = "Sai", 
						La_Name = "Kumar" }, 
			new StudentsDetails(){ Fir_Name = "Himesh", 
						La_Name = "Rai" } 
	}; 
	// Calling sort method by passing comparator 
	// function as an argument 
	//the sort method is called using the passing comparator
	Array.Sort(stud, new StudentComparator()); 
	//The print statement to display the elements
	foreach(var it in stud) 
	{ 
		Console.WriteLine(it.Fir_Name + ' ' + 	it.La_Name); 
	} 
} 
}

Output:

Output

Somesh Jaiswal
Sai Kumar
Himesh Rai

Explanation:

The program defines a class named StudentsDetails to indicate the details of a student. It has three properties: IdName, FirName , and La_Name . The program also details a class called StudentComparator that implements the IComparer interface. These operations compare two StudentsDetails objects based on the last name of the objects.It uses CaseInsensitiveComparer.Compare class to do a case-insensitive comparison of the last names.

The main method invokes the construction of an array of StudentsDetails struct as it is initialised with some sample data. The call on the Array.Sort method is made after that, sending the array of students and an instance of the StudentComparator class as the parameters. This sorts the array by students' last names.

Using LINQ query

We can as well access an already sorted objects array by the LINQ queries By the LINQ queries. The LINQ query is the 'from' keyword, and the 'GroupBy' keyword guides the syntax and. Once the keywords are used, we can take different types of standard query operations comprising filtering, grouping, etc., according to our requirements through the query.

Example:

Let us take a program to implement how to Sort-Object Array by using LinQ query in C#.

Example

using System;
using System.Linq;

class SortObjectOrder
{
    // the student class details
    class StudentsInfo
    {
        public int Is_Name { get; set; }
        public string Fir_Name { get; set; }
        public string La_Name { get; set; }
    }

    // Driver code
    static public void Main()
    {
        StudentsInfo[] stud = {
            new StudentsInfo(){ Fir_Name = "Sonu", La_Name = "Jaiswal" },
            new StudentsInfo(){ Fir_Name = "Sai", La_Name = "Kiran" },
            new StudentsInfo(){ Fir_Name = "Himesh", La_Name = "Raju" }
        };

        var sortedStu= stud.OrderBy(stud => stud.La_Name);

        // Display the sorted elements
        foreach (var it in sortedStu)
        {
            Console.WriteLine(it.Fir_Name + ' ' + it.La_Name);
        }
    }
}

Output:

Output

Sonu Jaiswal
Sai Kiran
Himesh Raju

Explanation:

The code specifies a class named StudentsInfo that deals with student information. It has three properties: Saludos, mi nombre es Name Pronouncione mi nombre . The IsName property contains an integer, while FirName and LaName represent string properties.

The Main method is the doorway to a program. It creates an array of StudentObjects named stud consisting of three elements. Each element depicts a student and assigns property values that represent the FirName and LaName properties.

The OrderBy method sorts the stud array in ascending order by the LaName attribute. This method returns a new collection of the elements sorted in the given order. The LaName,=> stud syntax is a lambda expression that specifies the key selector to use for sorting.

The sorted student's array is sortedStu . After that, it moves over to the sortedStu collection using a foreach loop. During each sort, the algorithm gets a variable from a collection and prints the FirName and LaName properties to the console.

Conclusion:

Sorting object arrays in C# by a specific property can be accomplished through two main methods: By applying Array.Sort, sorting operations, and involving the LINQ queries . The Array.Sort method implied representing a custom comparator class that was an IComparer interface implementer for a comparison based on the property the user selects, like L_ Name. The technique is efficient and easy to scale for large datasets.

While LINQ queries are more expressive and, therefore, more readable, traditional queries may sometimes be used due to performance reasons. In this example of LINQ, the OrderBy method is used to sort the array based on the given property. One of the major advantages of LINQ is that it has a declarative syntax. It helps in code readability and gives you choices to construct queries for several operations.

It is conditioned that the choice of these methods depends on different parameters such as code reading, ease of implementation, and performance requirements. Most of the time, LINQ queries are preferred for their readable nature, while Array.Sort can be used in performance-sensitive scenarios. In summary, the choice will depend on the exact needs and preferences of the developer, who will have to achieve a balance between the convenience of the main task and its efficiency.

Input Required

This code uses input(). Please provide values below: