Linq ToLookup Method in C#

Linq ToLookup Method in C# with example

In this article, I am going to discuss the Linq ToLookup Method in C# with some examples. Please read our previous article before proceeding to this article where we discussed the Linq GroupBy Operator with Multiple Keys with some examples. As part of this article, we are going to discuss the following pointers.

  1. What is Linq ToLookup Method?
  2. Examples of using the ToLookup method in C# using bothe Method and Query Syntax.
  3. How to use the ToLookup method with the OrderBy method?
  4. How to use the Linq ToLookup method in C# with Multiple Keys in C#?
  5. What is the difference between ToLookup and GroupBy method in Linq?
What is Linq ToLookup Operator?

The Linq ToLookup Method in C# exactly does the same thing as the GroupBy Operator does in Linq. The only difference between these two methods is the GroupBy method uses deferred execution whereas the execution of the ToLookup method is immediate. Please read the following article to understand what is Deferred and Immediate Execution in Linq queries.

Deferred Execution VS Immediate Execution in C#.

Student Helper class:

We are going to use the following Student Helper class in this demo. Please create a class file and then just copy and paste the following code in it.

using System.Collections.Generic;
namespace GroupByDemo
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Barnch { get; set; }
        public int Age { get; set; }

        public static List<Student> GetStudents()
        {
            return new List<Student>()
        {
            new Student { ID = 1001, Name = "Preety", Gender = "Female",
                                         Barnch = "CSE", Age = 20 },
            new Student { ID = 1002, Name = "Snurag", Gender = "Male",
                                         Barnch = "ETC", Age = 21  },
            new Student { ID = 1003, Name = "Pranaya", Gender = "Male",
                                         Barnch = "CSE", Age = 21  },
            new Student { ID = 1004, Name = "Anurag", Gender = "Male",
                                         Barnch = "CSE", Age = 20  },
            new Student { ID = 1005, Name = "Hina", Gender = "Female",
                                         Barnch = "ETC", Age = 20 },
            new Student { ID = 1006, Name = "Priyanka", Gender = "Female",
                                         Barnch = "CSE", Age = 21 },
            new Student { ID = 1007, Name = "santosh", Gender = "Male",
                                         Barnch = "CSE", Age = 22  },
            new Student { ID = 1008, Name = "Tina", Gender = "Female",
                                         Barnch = "CSE", Age = 20  },
            new Student { ID = 1009, Name = "Celina", Gender = "Female",
                                         Barnch = "ETC", Age = 22 },
            new Student { ID = 1010, Name = "Sambit", Gender = "Male",
                                         Barnch = "ETC", Age = 21 }
        };
        }
    }
}
Example:

The following example uses the ToLookup Method to organize the students into groups based on Branch as the key. Here, the key will be branch and the collection will be the student belongs to that particular branch.

using System;
using System.Linq;

namespace GroupByDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Method Syntax
            var GroupByMS = Student.GetStudents().ToLookup(s => s.Barnch);

            //Using Query Syntax
            var GroupByQS = (from std in Student.GetStudents()
                             select std).ToLookup(x => x.Barnch);

            //It will iterate through each group
            foreach (var group in GroupByMS)
            {
                Console.WriteLine(group.Key + " : " + group.Count());

                //Iterate through each student of a group
                foreach (var student in group)
                {
                    Console.WriteLine("  Name :" + student.Name + ", Age: " + student.Age + ", Gender :" + student.Gender);
                }
            }
            
            Console.Read();
        }
    }
}

Output:

Linq ToLookup Operator in C# with example

Example:

In the following example, we use the Linq ToLookup operator to get the employees by Gender. But here we sort the data first by Gender in descending order and then sort the data by the name in ascending order.

using System;
using System.Linq;

namespace GroupByDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var GroupByMS = Student.GetStudents().ToLookup(s => s.Gender)
                            .OrderByDescending(c => c.Key)
                            .Select(std => new
                            {
                                Key = std.Key,
                                Students = std.OrderBy(x => x.Name)
                            });
 
            foreach (var group in GroupByMS)
            {
                Console.WriteLine(group.Key + " : " + group.Students.Count());
                foreach (var student in group.Students)
                {
                    Console.WriteLine("  Name :" + student.Name + ", Age: " + student.Age + ", Branch :" + student.Barnch);
                }
            }

            Console.Read();
        }
    }
}

Output:

Linq ToLookup Operator with OrderBy in C# with example

Using ToLookup with Multiple Keys in C#:

The following example uses ToLookup to group the students first by Branch and then by Gender. The student’s groups first sorted by Branch in descending order and then by Gender in ascending order. Finally, we sort the data in each group by the name in ascending order.

using System;
using System.Linq;

namespace GroupByDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var ToLookupwithMultipleKeys = Student.GetStudents()
                                        .ToLookup(x => new { x.Barnch, x.Gender })
                                        .OrderByDescending(g => g.Key.Barnch).ThenBy(g => g.Key.Gender)
                                        .Select(g => new
                                        {
                                            Branch = g.Key.Barnch,
                                            Gender = g.Key.Gender,
                                            Students = g.OrderBy(x => x.Name)
                                        });
            
            foreach (var group in ToLookupwithMultipleKeys)
            {
                Console.WriteLine($"Barnch : {group.Branch} Gender: {group.Gender} No of Students = {group.Students.Count()}");
                
                foreach (var student in group.Students)
                {
                    Console.WriteLine($"  ID: {student.ID}, Name: {student.Name}, Age: {student.Age} ");
                }
                Console.WriteLine();
            }

            Console.Read();
        }
    }
}

Output:

Linq ToLookup with Multiple Keys

In the next article, I am going to discuss the Joins in Linq with examples. Here, in this article, I try to explain the ToLookup Method in LINQ with some examples. I hope you understood the need and use of the Linq ToLookup Method in C# with examples.

Leave a Reply

Your email address will not be published. Required fields are marked *