ToLookup

Okay, so what is ToLookup and how do you use it? The ToLookup operation can be thought of as a list with lookup capabilities. Similar to a Dictionary but the one advantage that it can contain duplicate keys. Duplicate keys!? What? Yes, duplicate keys. In a standard Dictionary, you can't have duplicate keys, otherwise, it will blow up. Whereas in a Lookup, you can. Why might this be useful? Well, the example below may illustrate.

Basic example

Here we have a list of people with Name, Gender and City properties. Now, let's say we want to look at people's names by cities. What we can do is specify the lookup key as the city, arg => arg.City and the value will be arg => arg.Name

If you notice there are three people from London and one person from Paris. When we call lookup["London"] we will get three names, Vernon, Carrie and Joanna. When we call lookup["Paris"] we will get just Thomas.

Live example: https://dotnetfiddle.net/LbWPIH

var people = new[]
    {
        new
            {
                Name = "Vernon",
                Gender = "Male",
                City = "London",

            },
        new
            {
                Name = "Carrie",
                Gender = "Female",
                City = "London"
            },
            new
            {
                Name = "Joanna",
                Gender = "Female",
                City = "London"
            },
        new
            {
                Name = "Thomas",
                Gender = "Male",
                City = "Paris"
            }
    };


ILookup<string, string> lookup = people.ToLookup(arg => arg.City, arg => arg.Name);

IEnumerable<string> peopleInLondon = lookup["London"];
IEnumerable<string> peopleInParis = lookup["Paris"];

// output:

// People in London
// Vernon
// Carrie
// Joanna

// People in Paris
// Thomas