Sorting an array of objects

If we need to sort an array of objects, then  the Array class’s defaut Sort message will not work as it is designed for primitive data types, like double, int, string, float etc. In that case, we need to implement the IComparable interface and define CompareTo method to perform the sorting.

In the following, we have a class Person, that stores FirstName and LastName of a person, and we want to sort an array of objects of this class. So we first inherit class from IComparable and then define the function CompareTo

The function CompareTo gives first preference in sorting to FirstName and then second preference to LastName

Here is an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
    class Person : IComparable<Person>
    {
        public string FirstName;
        public string LastName;

        public Person(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }

        public int CompareTo(Person other)
        {
            if (other == null)
                return 1;

            int result = string.Compare(this.FirstName, other.FirstName);

            if(result == 0)
            {
                result = string.Compare(this.LastName, other.LastName);
            }

            return result;
        }
    }

    

    class Program
    {
        static void Main(string[] args)
        {

            Person[] persons = {
                           new Person("Faisal", "Shah"),
                           new Person("Noman","Farooq"),
                           new Person("Khan", "Javed"),
                           new Person("Ali", "Shah"),
                           new Person("Ali", "Zia")
                         };

            Array.Sort(persons);

            foreach(var p in persons)
            {
                Console.WriteLine(p.FirstName + " " + p.LastName);
            }

        }
    }
}

 

Add a Comment

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