ToLookup Extension Method explained

The built-in Enumerable.cs contains various extension methods for IEnumerable interface. One of the method will be ToLookup() which is explained below:

The ToLookup() method can be used to quickly create lookup items based on different conditions.

E.g.: In a list of Employee objects it can create lookup list based on the Age of each employee.

Operates on: IEnumerable

Returns: ILookup<T1, T2>

Please note that the return value is a an interface of ILookup which contains 2 generic arguments. The first generic argument performs as the key and the values will be an IEnumerable of the original type.


Now let us take a more real time example where we have a series of Employee objects having Id, Age and Name as the properties. We need to create a lookup list based on their age. The result will be having Age as key and the corresponding Employee objects.

The class representation of Employee is given below:


In the following code we can see 6 employee objects are created with age 20 and 30. By using the ToLookup() method we are finding the employees of age 20.

        static void Main(string[] args)
            IList<Employee> list = new List<Employee>();
            list.Add(new Employee() { Id = 1, Age = 20, Name = "Kavin" });
            list.Add(new Employee() { Id = 2, Age = 30, Name = "Alen" });
            list.Add(new Employee() { Id = 3, Age = 20, Name = "Suresh" });
            list.Add(new Employee() { Id = 4, Age = 30, Name = "Jay" });
            list.Add(new Employee() { Id = 5, Age = 20, Name = "Nanda" });

            ILookup<int, Employee> lookupList = list.ToLookup(employee => employee.Age);

            Console.WriteLine("Employee with Age 20 are following:");
            foreach (Employee employee in lookupList[20])


The result of the above code will be Employee objects with Age = 20:

1 Kavin
3 Suresh
5 Nanda

Source Code

The attached source contains the ToLookup() sample with the associated console application.

Similar Articles