24 May 2015

Why and when to use IComparer

Assume for a while you are developing an e-commerce site which allows customers to sort the products in ascending, descending order of price and product title. And if sorting options aren't provided by your products data provider, then you have to implement sorting logic in C# .NET code.

To implement sorting you could think of System.IComparable interface. Your Product entity class can implement IComparable interface CompareTo() method. Inside the CompareTo() method, you can have logic to meet one kind of products sorting requirement. But requirement is, products should be displayed based on multiple sorting options.

So when there is need of such multiple sort order requirement, IComparer interface will come to your rescue. Let's first have look at definition of IComparer interface.

public interface IComparer 
{
   int Compare(T x, T y);
}
  • IComparer interface has a method called Compare() and it's accepting two parameters of type T.
  • The Compare() method returns a integer value. The return value will be zero when if both x and y are equal, +1 if X > Y else its -1.

Enough of theory, let's implement a Comparer for product to sort products based on product name ascending order.

public class ProductNameComparer:IComparer
 {
   public int Compare(Product x, Product y)
     {
       return x.Name.CompareTo(y.Name);
     }
 }

Similarly you can implement another product comparer to sort products based on their price descending order.

public class ProductPriceComparer:
     IComparer<Product>
 {
   public int Compare(Product x, Product y)
    {
      return y.Price.CompareTo(x.Price);
    }
 }

Now let's see usage of our custom comparer classes implementing IComparer interface.

List<Product> products = new List<Product>();
products.Add(new Product() { 
           Name="Cell phone", Price=2});

  products.Add(new Product() { 
           Name = "Laptop", Price = 3 });

products.Add(new Product() { 
           Name = "Apple Fruit", Price = 1 });

Let's see how to sort product based on their price descending order using the comparer. List class has Sort method which accepts the IComparer implementation. Below is the code listing for the same.

//sort the products by their price
products.Sort(new ProductPriceComparer());

After the above sorting code executed, products will be sorted based on their price in descending order.

Name: Laptop & Price: 3
Name: Cell phone & Price: 2
Name: Apple Fruit & Price: 1

Similarly you can use ProductNameComparer to sort products based on their name in ascending order.

//sort the products by their price
products.Sort(new ProductPriceComparer());

After the above sorting code executed, products will be sorted based on their price in descending order.

Name: Apple Fruit & Price: 1
Name: Cell phone & Price: 2
Name: Laptop & Price: 3

No comments:

Post a Comment