Single Key Multiple Values Data Structure for one to many mapping
- by nijhawan.saurabh
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 }
Normal
0
false
false
false
EN-US
X-NONE
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin-top:0in;
mso-para-margin-right:0in;
mso-para-margin-bottom:10.0pt;
mso-para-margin-left:0in;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}