psotirov

BiDictionary

Jun 16th, 2013
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace _03_BiDictionary
  5. {
  6.     class BiDictionary<TKey1, TKey2, TValue>
  7.     {
  8.         private readonly Dictionary<TKey1, List<TValue>> key1;
  9.         private readonly Dictionary<TKey2, List<TValue>> key2;
  10.         private readonly Dictionary<Tuple<TKey1, TKey2>, List<TValue>> bothKeys;
  11.         public int Count { get; private set; }
  12.  
  13.         public BiDictionary()
  14.         {
  15.             this.key1 = new Dictionary<TKey1, List<TValue>>();
  16.             this.key2 = new Dictionary<TKey2, List<TValue>>();
  17.             this.bothKeys = new Dictionary<Tuple<TKey1, TKey2>, List<TValue>>();
  18.             this.Count = 0;
  19.         }
  20.  
  21.         public void Add(TKey1 key1, TKey2 key2, TValue value)
  22.         {
  23.             // Adds value to key1 dictionary
  24.             if (!this.key1.ContainsKey(key1))
  25.             {
  26.                 this.key1.Add(key1, new List<TValue>());                
  27.             }
  28.  
  29.             if (this.key1[key1].Contains(value))
  30.             {
  31.                 throw new ArgumentException("Duplicated value");
  32.             }
  33.  
  34.             this.key1[key1].Add(value);
  35.  
  36.             // Adds value to key2 dictionary
  37.             if (!this.key2.ContainsKey(key2))
  38.             {
  39.                 this.key2.Add(key2, new List<TValue>());
  40.             }
  41.  
  42.             this.key2[key2].Add(value);
  43.  
  44.             // Adds value to both key1 and key2 dictionary
  45.             var both = new Tuple<TKey1, TKey2>(key1, key2);
  46.             if (!this.bothKeys.ContainsKey(both))
  47.             {
  48.                 this.bothKeys.Add(both, new List<TValue>());
  49.             }
  50.  
  51.             this.bothKeys[both].Add(value);
  52.             this.Count++;
  53.         }
  54.  
  55.         public ICollection<TValue> this[TKey1 key1]
  56.         {
  57.             get
  58.             {
  59.                 return this.key1[key1].ToArray();
  60.             }
  61.         }
  62.  
  63.         public ICollection<TValue> this[TKey2 key2]
  64.         {
  65.             get
  66.             {
  67.                 return this.key2[key2].ToArray();
  68.             }
  69.         }
  70.  
  71.         public ICollection<TValue> this[TKey1 key1, TKey2 key2]
  72.         {
  73.             get
  74.             {
  75.                 var both = new Tuple<TKey1, TKey2>(key1, key2);
  76.                 return this.bothKeys[both].ToArray();
  77.             }
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment