Sorting Genric List By Their Properties

This tip demonstrates how to sort generic lists in a much simpler way without writing  much complex loops and comparison logic.

The following steps are required for sorting the list:

1. Create class for sorting and implement interface IComparable wheres Type will reflect class for comparison
Ex:  public class Racer : IComparable

2. Add properties in the above class
Ex:

public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Country { get; set; }
        public int Wins { get; set; }

3. You have to override method of IComparable but it won’t be executed for sorting Ex:

public int CompareTo(Racer other)

4. Create a class for doing comparison which will implement IComparer for doing comparison Ex:

public class RacerComparer : IComparer

5. Add enum to save what will be items through sorting will be done. Ex:

public enum CompareType

6. Override compare function of IComparer Ex:

public int Compare(Racer x, Racer y)

You are done.

The complete code:

class Program
    {
        static void Main(string[] args)
        {
            //Create list of Racers
            List racers = new List();
            racers.Add(new Racer() { FirstName = "Vikash", LastName = "Kumar", Country = "India", Wins = 40 });
            racers.Add(new Racer() { FirstName = "Graham", LastName = "Hill", Country = "UK", Wins = 14 });
            racers.Add(new Racer() { FirstName = "Emerson", LastName = "Fittipaldi", Country = "Brazil", Wins = 14 });
            racers.Add(new Racer() { FirstName = "Mario", LastName = "Andretti", Country = "USA", Wins = 12 });
            racers.Add(new Racer() { FirstName = "Michael", LastName = "Schumacher", Country = "Germany", Wins = 91 });
            racers.Add(new Racer() { FirstName = "Mika", LastName = "Hakkinen", Country = "Finland", Wins = 20 });
            racers.Add(new Racer() { FirstName = "Alain", LastName = "Prost", Country = "France", Wins = 51 });
            racers.Add(new Racer() { FirstName = "Niki", LastName = "Lauda", Country = "Austria", Wins = 25 });
 
            //Sort racer by passing RacerComparer instance with type of sorting that is required
            racers.Sort(new RacerComparer(RacerComparer.CompareType.Wins));
 
            //Display result on Console
            racers.ForEach(Console.WriteLine);
 
        }
    }
 
    /// 
    /// Class for storing Racer specific details and behaviour
    /// 
    public class Racer : IComparable
    {
        //properties for class
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Country { get; set; }
        public int Wins { get; set; }
 
        /// 
        /// Overrided method of ToString()
        /// 
        /// Racer's First name and Last Name
        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
 
        /// 
        /// Overrided method of IComparable()
        /// Compares with current instance on their name
        /// 
        /// Racer object
        /// returns integer whether comparison is successuful or not
        public int CompareTo(Racer other)
        {
            int compare = this.LastName.CompareTo(other.LastName);
            if (compare == 0)
                return this.FirstName.CompareTo(other.FirstName);
            return compare;
        }
    }
 
    /// 
    /// Racer compare class
    /// 
    public class RacerComparer : IComparer
    {
        //Type of comparison needed
        public enum CompareType
        {
            FirstName,
            LastName,
            Country,
            Wins
        }
 
        private CompareType compareType;
 
        /// 
        /// Cunstructor for intializing RacerComparer with CompareType
        /// 
        /// Type of comparison
        public RacerComparer(CompareType compareType)
        {
            this.compareType = compareType;
        }
 
        /// 
        /// Comaparison between two objects
        /// sorting will be done by this method
        /// 
        /// First racer object
        /// Second racer object
        /// returns integer whether comparison is successuful or not
        public int Compare(Racer x, Racer y)
        {
            if (x == null) throw new ArgumentNullException("x");
            if (y == null) throw new ArgumentNullException("y");
 
            int result;
 
            //do comparison basis on CompareType and return result
            switch (compareType)
            {
                case CompareType.FirstName:
                    return x.FirstName.CompareTo(y.FirstName);
                case CompareType.LastName:
                    return x.LastName.CompareTo(y.LastName);
                case CompareType.Country:
                    if ((result = x.Country.CompareTo(y.Country)) == 0)
                        return x.LastName.CompareTo(y.LastName);
                    else
                        return result;
                case CompareType.Wins:
                    return y.Wins.CompareTo(x.Wins);
                default:
                    throw new ArgumentException("Invalid Compare Type");
            }
 
        }
    }
150 150 Burnignorance | Where Minds Meet And Sparks Fly!