How to Sort Object Array By Specific Property in C#?
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() 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);
}
}
}
OutputHitesh 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);
}
}
}
OutputHitesh Kumar
Bhuwaneh Nainwal
Anil Thapa
Similar Reads
How to use Array.BinarySearch() Method in C# | Set -1
Array.BinarySearch() method is used to search a value in a sorted one dimensional array. The binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the
13 min read
How to Get a Comma Separated String From an Array in C#?
Given an array, now our task is to get a comma-separated string from the given array. So we can do this task using String.Join() method. This method concatenates the items of an array with the help of a comma separator between each item of the array. Syntax: String.Join(",", array_name)Where array_n
2 min read
C# Program to Split a String Collections into Groups
Given a collection of strings and you are required to split them into groups using C#. The standard query operator contains GroupBy grouping operator using which we can split a collection of strings easily. The working of the GroupBy operator is similar to the SQL GroupBy clause. It is used to retur
3 min read
C# Program to Sort a List of Employees Based on Salary using LINQ
Given a list of employees, now we sort the list of employees according to their salary using LINQ. So to this task, we use the OrderBy() method. This method is used to sort the elements of the specified sequence in ascending order. Example: Input: {id = 101, Name = Rohit, Salary = 50000, Department
3 min read
How to Remove Duplicate Values From an Array in C#?
To remove duplicate values from an array in C#, you can use different approaches based on your requirements. So to do this we use the Distinct() function. HashSet, Using a Loop.This function gives distinct values from the given sequence. This method will throw ArgumentNullException if the given arra
3 min read
C# Program to Find Integer Numbers from the List of Objects and Sort them Using LINQ
Given a list of objects, we need to find the integer double numbers from the list of objects and sort them using LINQ. So this task can be done using the OfType() method and then the sorting of numbers can be done by using OrderBy() method. Let discuss them one by one along with their syntax: 1. OfT
2 min read
C# Program to Sort a List of String Names Using the LINQ OrderBy() Method
Given a list of string names, now our task is to sort the names given in the list using the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. While using this method in the LINQ query you don't need to add an extra condition to sort the list in
2 min read
C# Program to Sort Student Names in Descending Order using LINQ
Given a list of student names, now our task is to sort the names given in the list in descending order using the LINQ, This task can be done using OrderByDescending() method of LINQ. This method is used to sort the elements in the collection in descending order. While using this method in the LINQ q
2 min read
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
Given a list of integers, now our task is to sort the given list of integers. So we use the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. This method is overloaded in two different ways: OrderBy<TSource, TKey>(IEnumerable<TSource
2 min read
C# Program to Sort a List of Employees Based on Salary and Whose Department is ABC using LINQ
Given a list of employees, now our task is to sort the given list of employees based on salary and whose department is ABC using LINQ. Example: Input: {id = 101, name = "Sumit", salary = 10000, department = ABC} {id = 102, name = "Rohit", salary = 20000, department = HR} {id = 103, name = "Mohit", s
2 min read