Friday, 18 October 2013

LINQ Sample - Group Products by Category

Following example orders List<Product> by Product.Category and saves the grouped result into a Dictionary<string, List<Product>>.

 public class Product
{
   public string Name { get; set; }
   public string Category { get; set; }
}

  List<Product> products = new List<Product>{
                new Product{ Name = "Beans", Category = "Veg" },
                new Product{ Name = "Apple", Category = "Fruit" },
                new Product{ Name = "Tomato", Category = "Veg" },
                new Product{ Name = "Orange", Category = "Fruit" },
            };

Dictionary<string, List<Product>> productCategories =
                (from p in products
                group p by p.Category into g
                select new { Category = g.Key, Products = g }
                )
.ToDictionary(categories => categories.Category, categories =>
categories.Products.ToList<Product>());    

Now you can order the result by Category name, that is the Key of Dictionary

var productCategoriesOrderd = 
productCategories.OrderBy(productCategory => 
productCategory.Key);

No comments:

Post a Comment