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#
using System;
using System.Collections;
class GFG{
class StudentComparer : IComparer
{
public int Compare( object x, object y)
{
return ( new CaseInsensitiveComparer()).Compare(((Student)x).LastName,
((Student)y).LastName);
}
}
class Student
{
public int Id
{
get ;
set ;
}
public string FirstName
{
get ;
set ;
}
public string LastName
{
get ;
set ;
}
}
static public void Main()
{
Student[] students = {
new Student(){ FirstName = "Bhuwanesh" ,
LastName = "Nainwal" },
new Student(){ FirstName = "Anil" ,
LastName = "Thapa" },
new Student(){ FirstName = "Hitesh" ,
LastName = "Kumar" }
};
Array.Sort(students, new StudentComparer());
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#
using System;
using System.Collections;
class GFG{
class StudentComparer : IComparer
{
public int Compare( object x, object y)
{
return ( new CaseInsensitiveComparer()).Compare(((Student)x).LastName,
((Student)y).LastName);
}
}
class Student
{
public int Id
{
get ;
set ;
}
public string FirstName
{
get ;
set ;
}
public string LastName
{
get ;
set ;
}
}
static public void Main()
{
Student[] students = {
new Student(){ FirstName = "Bhuwanesh" ,
LastName = "Nainwal" },
new Student(){ FirstName = "Anil" ,
LastName = "Thapa" },
new Student(){ FirstName = "Hitesh" ,
LastName = "Kumar" }
};
Array.Sort(students, new StudentComparer());
foreach ( var item in students)
{
Console.WriteLine(item.FirstName + ' ' +
item.LastName);
}
}
}
|
Output
Hitesh Kumar
Bhuwaneh Nainwal
Anil Thapa
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
15 Feb, 2022
Like Article
Save Article