LINQ (C#): GroupBy - SingleKey, MultiKey and Grouping with Sorting

In this tutorial, you will learn:
  1. What is GroupBy Operator in LINQ?
  2. How to use GroupBy to grouping data?
  3. Single Key Grouping with Example
  4. Multi Key Grouping with Example
  5. Grouping with Sorting
  6. Programming Example

GroupBy operator projects data in groups based on common attribute or key. It is a great tool when you want to see the summarize result based on group. In this article, I have written several programs that is easy to understand and will help you to understand GropuBy operator.

Single key Grouping

In Single Key Grouping, the data is organized based on the single key input.


Programmin Example
using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTutorial
{
    class ProductStore
    {       
        public int category { get; set; }
        public string productName { get; set; }

        public string type { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Creating List
            IList<ProductStore> productList = new List<ProductStore>();

            productList.Add(new ProductStore { category = 1, productName = "Hard Disk", type = "MEMORY" });
            productList.Add(new ProductStore { category = 2, productName = "Monitor", type = "DISPLAY" });          
            productList.Add(new ProductStore { category = 1, productName = "SSD Disk", type = "MEMORY" });
            productList.Add(new ProductStore { category = 1, productName = "RAM", type = "MEMORY" });
            productList.Add(new ProductStore { category = 2, productName = "Processor", type = "CPU" });
            productList.Add(new ProductStore { category = 1, productName = "Bluetooth", type = "Accessories" });
            productList.Add(new ProductStore { category = 2, productName = "Keyboard & Mouse", type = "Accessories" });

            //Query Syntax
            var result = from product in productList
                         group product by product.category;
            
            //Method Syntax. Uncomment it to see the output 
            //var result = productList.GroupBy(p => p.category);

            foreach(var group in result)
            {
                Console.WriteLine(string.Format("Category: {0}", group.Key));
                foreach(var name in group)
                {
                    Console.WriteLine(string.Format("\tProduct Name: {0} | Type: {1}", name.productName, name.type));
                }
            }

            Console.ReadKey();
        }
    }
}

If you want to use Method Syntax or lambda expression then you can use following structure to display result.

var result = productList.GroupBy(p => p.category);

Output:


Category: 1
        Product Name: Hard Disk | Type: MEMORY
        Product Name: SSD Disk | Type: MEMORY
        Product Name: RAM | Type: MEMORY
        Product Name: Bluetooth | Type: Accessories
Category: 2
        Product Name: Monitor | Type: DISPLAY
        Product Name: Processor | Type: CPU
        Product Name: Keyboard & Mouse | Type: Accessories

_


Multi Key Grouping

In multi key grouping, you can use more than one key to summarize and grouping data. Here, in this example, I will use category and type as a key to grouping data.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTutorial
{
    class ProductStore
    {       
        public int category { get; set; }
        public string productName { get; set; }

        public string type { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Creating List
            IList<ProductStore> productList = new List<ProductStore>();

            productList.Add(new ProductStore { category = 1, productName = "Hard Disk", type = "MEMORY" });
            productList.Add(new ProductStore { category = 2, productName = "Monitor", type = "DISPLAY" });          
            productList.Add(new ProductStore { category = 1, productName = "SSD Disk", type = "MEMORY" });
            productList.Add(new ProductStore { category = 1, productName = "RAM", type = "MEMORY" });
            productList.Add(new ProductStore { category = 2, productName = "Processor", type = "CPU" });
            productList.Add(new ProductStore { category = 1, productName = "Bluetooth", type = "Accessories" });
            productList.Add(new ProductStore { category = 2, productName = "Keyboard & Mouse", type = "Accessories" });

            //Query Syntax
            var result = from product in productList
                         group product by new { product.category, product.type };
            
            //Method Syntax. Uncomment it to see the output 
            //var result = productList.GroupBy(p => new { p.category, p.type });

            foreach(var group in result)
            {
                Console.WriteLine(string.Format("Category: {0} | Type: {1}", group.Key.category, group.Key.type));
                foreach(var name in group)
                {
                    Console.WriteLine(string.Format("\tProduct Name: {0} | Type: {1}", name.productName, name.type));
                }
            }

            Console.ReadKey();
        }
    }
}

If you want to use Method Syntax or Lambda Expression, then you can use following structre.


var result = productList.GroupBy(p => new { p.category, p.type });
Output

Category: 1 | Type: MEMORY
        Product Name: Hard Disk | Type: MEMORY
        Product Name: SSD Disk | Type: MEMORY
        Product Name: RAM | Type: MEMORY
Category: 2 | Type: DISPLAY
        Product Name: Monitor | Type: DISPLAY
Category: 2 | Type: CPU
        Product Name: Processor | Type: CPU
Category: 1 | Type: Accessories
        Product Name: Bluetooth | Type: Accessories
Category: 2 | Type: Accessories
        Product Name: Keyboard & Mouse | Type: Accessories
_

Grouping with Sorting

You can also do both Grouping and Sorting simultaneously. To do that, you need to understand following programming example.

Programming Example
using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTutorial
{
    class ProductStore
    {       
        public int category { get; set; }
        public string productName { get; set; }

        public string type { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Creating List
            IList<ProductStore> productList = new List<ProductStore>();

            productList.Add(new ProductStore { category = 1, productName = "Hard Disk", type = "MEMORY" });
            productList.Add(new ProductStore { category = 2, productName = "Monitor", type = "DISPLAY" });          
            productList.Add(new ProductStore { category = 1, productName = "SSD Disk", type = "MEMORY" });
            productList.Add(new ProductStore { category = 1, productName = "RAM", type = "MEMORY" });
            productList.Add(new ProductStore { category = 2, productName = "Processor", type = "CPU" });
            productList.Add(new ProductStore { category = 1, productName = "Bluetooth", type = "Accessories" });
            productList.Add(new ProductStore { category = 2, productName = "Keyboard & Mouse", type = "Accessories" });

            //Query Syntax
            var result = from product in productList
                         group product by new { product.category, product.type } into pgroup
                         orderby pgroup.Key.category
                         select pgroup;


            //Method Syntax. Uncomment it to see the output 
            //var result = productList.GroupBy(p => new { p.category, p.type }).OrderBy(p => p.Key.category);

            foreach(var group in result)
            {
                Console.WriteLine(string.Format("Category: {0} | Type: {1}", group.Key.category, group.Key.type));
                foreach(var name in group)
                {
                    Console.WriteLine(string.Format("\tProduct Name: {0} | Type: {1}", name.productName, name.type));
                }
            }

            Console.ReadKey();
        }
    }
}

If you want to use Method Syntax or Lambda Expression, then you can use following structre.

var result = productList.GroupBy(p => new { p.category, p.type }).OrderBy(p => p.Key.category);

Category: 1 | Type: MEMORY
        Product Name: Hard Disk | Type: MEMORY
        Product Name: SSD Disk | Type: MEMORY
        Product Name: RAM | Type: MEMORY
Category: 1 | Type: Accessories
        Product Name: Bluetooth | Type: Accessories
Category: 2 | Type: DISPLAY
        Product Name: Monitor | Type: DISPLAY
Category: 2 | Type: CPU
        Product Name: Processor | Type: CPU
Category: 2 | Type: Accessories
        Product Name: Keyboard & Mouse | Type: Accessories
_

Summary

In this tutorial, I have tried to teach you Grouping in LINQ using the simple but complete programming example. In the next chapter, you will learn ToLookup operator in LINQ.

 

Share your thought