Nezir Zahirović

Generic List Sort() Implementing custom default sorting compare overload

In .NET 2.0 we are introduced with Generic lists  which ware most powerful feature of C# 2.0.
"Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code".

In this post I will present you how to implement an overload for the Generic List Sort() method. Working on one of my web projects I had it to implement default Sort() method for my Generic list object. After some investigation I find some useful post which shows me the easiest way to done this. Final goal was to implement my own default comparer for our object (Car).

Most important part is to create Class which will inherit IComparable and of course implement public int CompareTo(Car car) method.

So, let's we start...

In this sample I create new empty web site by choosing .net 2.0. After I added my Default.aspx page and Web.Config I had to Add new Class which I named as Car.cs:

Here you can see my Car class with properties and implementation of CompareTo method.

Next,  here is our Default.aspx code page where we use our default sort method.

..and here is sample result.

As you can see it  in this sample, it's very easy to implement default Sort() method in you generic list. Also, you can very easy change your default Sort() property type.

Car.cs class code:

using System;
using System.Collections.Generic;
using System.Web;
/// Summary description for Car

public class Car:IComparable
public Car(){}
            private string name;
            public string Name
       get { return name;}
       set { name = value;}
            private int age;
            public int Age
                get { return age; }
                set { age = value; }
            private int miles;
            public int Miles
                get { return miles; }
                set { miles = value; }
            private decimal price;
            public decimal Price
                get { return price; }
                set { price = value; }
            public int CompareTo(Car car)
                return this.Price.CompareTo(car.Price);

.... that's all for this post.