LINQ (C#) – ToLookup Operator Example and Tutorial

In this tutorial, you will learn:
  1. What is ToLookup Operator in LINQ?
  2. Programming Example

ToLookup operator is same as GroupBy operator and it is also used for grouping data based on key/value pair. Only difference between Group by and ToLookup operator is; execution of ToLookup Operator is immediate where as Group by is delayed. Apart from it, ToLookup operator can be used only with lambda expression or method syntax.

Reverse 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" });

            var result = productList.ToLookup(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();
        }
    }
}

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
_


Query Syntax

If you want to write Lookup method in query syntax then you can follow the given structure.

var result = (from product in productList select product).ToLookup(p => p.category);

Summary

In this tutorial, you learned, how to use ToLookup operator in LINQ with programming example. In the next chapter, you will learn Average method in LINQ.

 

Share your thought