• How to GroupBy LIST and convert to dictionary in LinQ

    Posted on July 31, 2012 by in C#, Dotnet

    In this example,  I am going create bunch of products with some sample data. Later, I will group them by subcategoryname using GroupBy clause in LinQ and then convert the grouped list into a generic dictionary.

    As you can see below, I have created a simple product class for our example.

    Product.cs:

    public class Product
    {
        public int ProductID;
        public string ProductName;
        public string ProductSubCategoryName;
    }
    

    I have created a helper method that would create a list of products populated with some sample data. Then I perform grouping on the list based on their subcategoryname property. Later I convert the grouped list into a dictionary by invoking ToDictionary function. Finally I iterate through the dictionary and display products on to the console.

    public static void GroupByAndConvertToDictionary()
    {
        //populate some sample data
        List<Product> products = new List<Product>();
    
        Product product = new Product();
        product.ProductID = 680;
        product.ProductName = "HL Road Frame - Black, 58";
        product.ProductSubCategoryName = "Brakes";
        products.Add(product);
    
        product = new Product();
        product.ProductID = 706;
        product.ProductName = "HL Road Frame - Red, 58";
        product.ProductSubCategoryName = "Road Bikes";
        products.Add(product);
    
        product = new Product();
        product.ProductID = 749;
        product.ProductName = "Road-150 Red, 62";
        product.ProductSubCategoryName = "Road Bikes";
        products.Add(product);
    
        product = new Product();
        product.ProductID = 907;
        product.ProductName = "Rear Brakes";
        product.ProductSubCategoryName = "Brakes";
        products.Add(product);
    
        product = new Product();
        product.ProductID = 953;
        product.ProductName = "Touring-2000 Blue, 60";
        product.ProductSubCategoryName = "Touring Bikes";
        products.Add(product);
    
        product = new Product();
        product.ProductID = 954;
        product.ProductName = "Touring-1000 Yellow, 46";
        product.ProductSubCategoryName = "Touring Bikes";
        products.Add(product);
    
        //group products by subcategory name
        Dictionary<string,List<Product>> productsHash = products.GroupBy(x => x.ProductSubCategoryName)
                                                                .OrderBy(p => p.Key.ToString())
                                                                .ToDictionary(x => x.Key, x => x.ToList());
    
        //iterate through product groups and print product attributes
        foreach (string subcategoryName in productsHash.Keys)
        {
            Console.WriteLine("Product SubCategory Name (key) {0}:", subcategoryName);
            Console.WriteLine();
            foreach (var prd in productsHash[subcategoryName])
            {
                Console.WriteLine("\tProduct ID:  " + prd.ProductID);
                Console.WriteLine("\tProduct Name:" + prd.ProductName);
                Console.WriteLine("\t----------------------------------------");
            }
            Console.WriteLine("/*****************************************************/");
        }
    }
    

    Output:

    Be Sociable, Share!
      Post Tagged with , ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]

    Leave a Reply