11.3. Creating a One-to-Many Map (MultiMap)

Problem

A Hashtable or a Dictionary<T,U> can map only a single key to a single value, but you need to map a key to one or more values. In addition, it may also be possible to map a key to null.

Solution

Use a Dictionary<T,U> with values that are a List<U>. This structure allows you to add multiple values (in the List<U>) for each key of the Dictionary<T,U>. The MultiMap<T,U> class shown in Example 11-4, which is used in practically the same manner as a Dictionary<T,U> class, does this.

Example 11-4. MultiMap class

using System; using System Collections; using System.Collections.Generic; public class MultiMap<TKey, UValue> : IDictionary<TKey, IList<UValue>> { private Dictionary<TKey, IList<UValue>> map = new Dictionary<TKey, IList<UValue>>(); public IList<UValue> this[TKey key] { get {return (map[key]);} set {map[key] = value;} } public void Add(TKey key, UValue item) { AddSingleMap(key, item); } public void Add(TKey key, IList<UValue> items) { foreach (UValue val in items) AddSingleMap(key, val); } public void Add(KeyValuePair<TKey, IList<UValue>> keyValuePair) { foreach (UValue val in keyValuePair.Value) AddSingleMap(keyValuePair.Key, val); } public void Clear() { map.Clear(); } public int Count { get {return (map.Count);} } public bool ContainsKey (TKey key) { return (map.ContainsKey(key)); } public bool ContainsValue(UValue item) { if (item == null) { foreach (KeyValuePair<TKey, IList<UValue>> kvp in map) { if (((List<UValue>)kvp.Value).Count ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.