Sorting Elements in a Object-based Array

Since most C# applications are taking advantage of object-oriented practices, we often end up with arrays of objects instead of simple-types like int.

Let’s imagine, we have a class like this:

[codesyntax lang=”csharp”]

public class Employee
{
	public string FirstName;
	public string LastName;
	public decimal Salary;
	public int EmpType;

}

[/codesyntax]

 

Then we have an application that creates arrays of Employee objects so we can store each instance of the object.  For example:

[codesyntax lang=”csharp”]

Employee[] myList = new Employee[2];

[/codesyntax]

Suppose I want to sort the array by a particular field of Employee?  How could we sort this array of Employee objects by the LastName field?

There are two ways we can accomplish this – delegates and LINQ

Delegates

A delegate is a special type that references a method.  You can define a parameter list and a return type just like you can in regular methods.  Through this delegate process, we can create a method that sorts the object array by comparison.

[codesyntax lang=”csharp”]

delegate(Employee emp1, Employee emp2)
{
	return emp1.LastName.CompareTo(emp2.LastName);
});

[/codesyntax]

The CompareTo method is built-in to the .NET framework and compares two objects of the same type. It will return less than 0 when X < Y, zero when X = Y and greater than 0 when X > Y.

LINQ

LINQ stands for Language-Integrated Query. It is a feature of the .NET framework and allows you to create queries based on simple patterns and built-in methods.   LINQ has a method OrderBy that is designed to compare and sort two elements.

[codesyntax lang=”csharp”]

var sortedArray = myList.OrderBy(emp => emp.LastName).ToList();

[/codesyntax]

Either of these methods will work when you have an array of objects that need to be sorted by one or more of their elements.  Make sure to let me know if you have questions!

One thought on “Sorting Elements in a Object-based Array”

  1. Good web site you have got here.. It’s hard to find quality writing like yours nowadays.
    I truly appreciate people like you! Take care!!

Leave a Reply

Your email address will not be published. Required fields are marked *