Single Key Multiple Values Data Structure for one to many mapping

Posted by nijhawan.saurabh on ASP.net Weblogs See other posts from ASP.net Weblogs or by nijhawan.saurabh
Published on Wed, 31 Oct 2012 06:58:00 GMT Indexed on 2012/10/31 11:01 UTC
Read the original article Hit count: 338

Filed under:
|
|
Dictionaries are good, they are great to store Key / Value pairs but what if you want to store multiple values for a single key?

Dictionaries would not allow duplicate keys.

I came across a nice way to represent such a Data Structure using one of the Extension Method (ToLookup) present in System.Linq Namespace which converts an IEnumerable<T> to an ILookup<TKey, TElement>.

 

Now, there are two parameters this method expects (The other overload expects 3 parameters):

  • IEnumerable<TSource> - This list would contain the actual data.
  • Func<TSource, TKey> keySelector - The Delegate which which computes the keys

 

The method returns the following:

ILookup<TKey, TElement>

 

This DS would store Keys and multiple values along those keys.

 

Let's see a small example:

 

 

   12  using System;

   13     using System.Collections.Generic;

   14     using System.Linq;

   15 

   16     /// <summary>

   17     /// </summary>

   18     internal class Program

   19     {

   20         #region Methods

   21 

   22         /// <summary>

   23         /// </summary>

   24         /// <param name="args">

   25         /// The args.

   26         /// </param>

   27         private static void Main(string[] args)

   28         {

   29             // Create an array of strings.

   30             var list = new List<string> { "IceCream1", "Chocolate Moose", "IceCream2" };

   31 

   32             // Generate a lookup Data Structure

   33             ILookup<int, string> lookupDs = list.ToLookup(item => item.Length);

   34 

   35           // Enumerate groupings.

   36             foreach (var group in lookupDs)

   37             {

   38                 foreach (string element in group)

   39                 {

   40                     Console.WriteLine(element);

   41                 }

   42             }

   43         }


© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about c#