In this guide, we will explore the process of arranging an Object Array based on a Specific Attribute. It is common to organize objects in arrays, especially when dealing with intricate data formats. In C#, it is possible to arrange array elements based on a specific attribute. For example, we can organize a list of employees by their salaries or sort a collection of products by their prices.
Sorting is the act of arranging elements in a specific sequence. It involves organizing elements in either ascending or descending order. For example, consider the array [1,13,16,10]; it can be sorted in ascending order as [1,10,13,16] or in descending order as [16,13,10,1], depending on the desired outcome. In C#, there are two common methods to sort an object array based on a specific property:
- Using Array.sort
- Employing a LINQ query
What is the Array.sort method?
The array.sort function is utilized to rearrange the elements within an array. This method offers a selection of 17 different variations, allowing us to pick a specific method for arranging objects according to a particular property.
In this scenario, Array represents a collection of elements that requires sorting.
Exceptions: It will display the subsequent error instances:
When individuals journey into space, adjusting to the unfamiliar surroundings can pose significant challenges.
When a null array object reference is encountered, the code will throw an ArgumentNullException with the message "Passed Array is null".
InvalidOperationException: The issue arises when one or more elements within the array do not conform to the requirements of the IComparable interface.
This software necessitates items within the collection named student to have a data type of Student. These items are categorized based on the identifier "_LName" associated with each student. The functionality is executed within a function of the StudentComparer class utilizing the Compare function.
Example:
Let's consider a code example to demonstrate how to arrange an array of objects by a particular property in C#.
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:
Somesh Jaiswal
Sai Kumar
Himesh Rai
Explanation:
The software creates a class named StudentRecord to represent student information. This class includes three attributes: IdentifierName, FirstName, and Surname. Additionally, there is a class named ComparatorStudent that utilizes the IComparer interface. This class compares two instances of StudentRecord by their surnames, employing the CaseInsensitiveComparer.Compare method for a case-insensitive evaluation.
The primary function triggers the creation of a StudentsDetails structure array, which is preloaded with sample information. Following this, the Array.Sort method is invoked, passing the students' array and a StudentComparator class instance as arguments. This action arranges the array based on the students' surnames.
Using LINQ query
We can also retrieve a pre-sorted array of objects using LINQ queries. The 'from' keyword initiates the LINQ query, while the 'GroupBy' keyword helps structure the syntax. By incorporating these keywords, we can perform various standard query operations such as filtering and grouping based on our specific needs.
Example:
Let's consider a code example to demonstrate how to sort an array of objects using a LinQ query in C#.
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:
Sonu Jaiswal
Sai Kiran
Himesh Raju
Explanation:
The code defines a class named StudentDetails responsible for managing student data. Within this class, there are three attributes: ```
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).LaName,((StudentsDetails)y).LaName);
}
}
// 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.FirName + ' ' + it.LaName);
}
}
}
Somesh Jaiswal
Sai Kumar
Himesh Rai
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{ FirName = "Sonu", LaName = "Jaiswal" },
new StudentsInfo{ FirName = "Sai", LaName = "Kiran" },
new StudentsInfo{ FirName = "Himesh", LaName = "Raju" }
};
var sortedStu= stud.OrderBy(stud => stud.La_Name);
// Display the sorted elements
foreach (var it in sortedStu)
{
Console.WriteLine(it.FirName + ' ' + it.LaName);
}
}
}
The Main function serves as the entry point to a program where it initializes an array called stud containing three StudentObjects. Each object in the array represents a student and sets values for the FirstName and LastName properties.
The OrderBy function arranges the array named stud in an ascending order based on the La_Name attribute. This function generates a fresh collection containing the sorted elements. The syntax La_Name,=> stud represents a lambda expression used to determine the sorting key.
The arranged list of students is stored in the sortedStu array. Next, it iterates through the sortedStu collection using a foreach loop. Within each iteration, the algorithm retrieves an element from the collection and displays the First_Name and Last_Name attributes on the console.
## Conclusion:
Arranging arrays of objects in C# based on a particular property can be achieved using two primary approaches: utilizing Array.Sort for sorting tasks and leveraging LINQ queries. The process involves using the Array.Sort() method along with a custom comparator class that implements the IComparer interface to compare objects based on the selected property, such as L_ Name. This method is effective and can be easily adapted for sorting large datasets.
While LINQ queries are known for being more expressive and easier to understand, conventional queries may still be preferred in certain cases for performance considerations. In the instance of LINQ demonstrated here, the OrderBy function is applied to arrange the array according to the specified property. A key benefit of LINQ is its declarative style, which enhances code clarity and provides flexibility in formulating queries for various tasks.
It is established that the selection of these approaches is contingent on various factors like code comprehension, implementation simplicity, and performance criteria. Frequently, LINQ queries are favored for their clarity, whereas Array.Sort() may be employed in situations where performance is crucial. To sum up, the decision will be influenced by the specific requirements and inclinations of the programmer, who must strike a harmony between the ease of accomplishing the primary objective and its effectiveness.