what is Lookup?

  • Dictionary and Lookup can be used as lookup structures, but there are some differences between the two.
  • Lookup has no public constructor and is immutable. Immutable means that we cannot add or remove items after creation.
  • Lookup can have duplicate keys
  • Lookup is created by the factory method ToLookup() found on classes that implement IEnumerable
  • Searching for a non-existing key will return an empty sequence instead of an exception
  • Another big difference is that Lookup maps to a collection of values, not a single value like Dictionary does.


Lookup lets you group items together by a key, but then access them via that key in an
efficient manner (rather than just iterating over them all, which is what GroupBy  lets you do).

One way to think about it is this: Lookup<TKey, TElement> is similar to
 Dictionary<TKey, Collection<TElement>>

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

public class Test
    static void Main()
        // Just types covering some different assemblies
        Type[] sampleTypes = new[] { typeof(List<>), typeof(string), 
                                     typeof(Enumerable), typeof(XmlReader) };

        // All the types in those assemblies
        IEnumerable<Type> allTypes = sampleTypes.Select(t => t.Assembly)
                                               .SelectMany(a => a.GetTypes());

        // Grouped by namespace, but indexable
        ILookup<string, Type> lookup = allTypes.ToLookup(t => t.Namespace);

        foreach (Type type in lookup["System"])
            Console.WriteLine("{0}: {1}", 
                              type.FullName, type.Assembly.GetName().Name);

ToLookup returns a data structure that allows indexing.





By Sriramjithendra Posted in C#.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s