Wednesday, January 16, 2013

Converting List of objects into Dictionary using Lambda Expression

Suppose we have a class 'Product' as below:


public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Location { get; set; }
 
        public Product(int id, string name, double price, string location)
        {
            this.ID = id;
            this.Name = name;
            this.Price = price;
            this.Location = location;
        }
 
        public static List<Product> GetSampleProducts()
        {
            return new List<Product> {
                                          new Product(1, "Mobile", 339.99, "ZZZ-B090-ZZZ-5"),
                                          new Product(2, "Laptop", 514.99, "RRRR-111-RRRR-2"),
                                          new Product(3, "Phone", 112.99, "AAAA-22-AAA"),
                                          new Product(4, "PC", 313.69, "WWW-343-WWWWWWW-03"),
                                          new Product(5, "AC", 413.99, "NNN-80-NNNN-342"),
                                          new Product(6, "Heater", 109.99, "TTTT-318-TTTTTTTT-424")
                                      };
        }
 
        public override string ToString()
        {
            return string.Format("The product '{0}' is at Location : {1} with price Tag : ${2}", Name, Location, Price);
        }
    }

Then we could easily convert that list of objects into a .Net Dictionary in one line if we use an useful extension method available in the List Collection and lambda expression in the following way:

            List<Product> lstProduct = Product.GetSampleProducts();
 
            Dictionary<int, Product> DictCollection1 = lstProduct.ToDictionary(x => x.ID, x => x);
 
 

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete