Saturday, June 28, 2014

LINQ Distincts with multiple properties from Generic List

This post describes how to get distinct rows from generic list by multiple fields or properties.

.Net Framework 4.5 provides IEqualityComparer Interface.

This interface allows the implementation of customized equality comparison for generic collections.

will go through step by step to how to use IEqualityComparer interface for distinct records.

Step 1 : First create one class

    public class Product
    {
        public int ProductID { get; set; }

        public string ProductName { get; set; }

        public string Code { get; set; }

        public double Price { get; set; }

        public int Quantity { get; set; }
    }

Step 2 : Create Comparer class for retrieve Distinct product by Quantity & Price.

    public class ProductComparer : IEqualityComparer
    {
        public bool Equals(Product x, Product y)
        {
            return (x.Quantity == y.Quantity && x.Price == y.Price);
        }
        public int GetHashCode(Product x)
        {
            return (x.Quantity.GetHashCode());
        }
    }

Equals method is used to check whether specified object are equals or not. i have used quantity and price in this equals method.

you can add more fields if you required for distinct result.
(for example : return (x.Code == y.Code && x.Price == y.Price); ) this will return distinct records by Code and Price properties.

Step 3 : Create List<product> object and insert some records.

List<Product> productList = new List<Product>();

productList.Add(new Product()
{
    ProductID = 1, Code = "ABC", Price = 10, ProductName = "Dairy Milk", Quantity = 5
});
productList.Add(new Product()
{
    ProductID = 2, Code = "DEF", Price = 20, ProductName = "Lux", Quantity = 40
});
productList.Add(new Product()
{
    ProductID = 3, Code = "GGG", Price = 10,  ProductName = "5Star", Quantity = 5
});
productList.Add(new Product()
{
    ProductID = 4, Code = "ABC", Price = 50, ProductName = "Himalaya Face Wash", 
    Quantity = 10
}); 


Step 4 :Create Linq query with above comparer class to generate distinct result.

List<Product> result = productList.Distinct(new ProductComparer()).ToList();

Above linq statement give list of product which has Quantity and Price are common in all rows.