| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
|
| 3 |
using System; |
| 4 |
using System.Collections.Generic; |
| 5 |
using System.Linq; |
| 6 |
|
| 7 |
namespace System.Reactive |
| 8 |
{ |
| 9 |
class Lookup<K, E> : ILookup<K, E> |
| 10 |
{ |
| 11 |
Dictionary<K, List<E>> d; |
| 12 |
|
| 13 |
public Lookup(IEqualityComparer<K> comparer) |
| 14 |
{ |
| 15 |
d = new Dictionary<K, List<E>>(comparer); |
| 16 |
} |
| 17 |
|
| 18 |
public void Add(K key, E element) |
| 19 |
{ |
| 20 |
var list = default(List<E>); |
| 21 |
if (!d.TryGetValue(key, out list)) |
| 22 |
d[key] = list = new List<E>(); |
| 23 |
list.Add(element); |
| 24 |
} |
| 25 |
|
| 26 |
public bool Contains(K key) |
| 27 |
{ |
| 28 |
return d.ContainsKey(key); |
| 29 |
} |
| 30 |
|
| 31 |
public int Count |
| 32 |
{ |
| 33 |
get { return d.Count; } |
| 34 |
} |
| 35 |
|
| 36 |
public IEnumerable<E> this[K key] |
| 37 |
{ |
| 38 |
get { return Hide(d[key]); } |
| 39 |
} |
| 40 |
|
| 41 |
private IEnumerable<E> Hide(List<E> elements) |
| 42 |
{ |
| 43 |
foreach (var x in elements) |
| 44 |
yield return x; |
| 45 |
} |
| 46 |
|
| 47 |
public IEnumerator<IGrouping<K, E>> GetEnumerator() |
| 48 |
{ |
| 49 |
foreach (var kv in d) |
| 50 |
yield return new Grouping(kv); |
| 51 |
} |
| 52 |
|
| 53 |
class Grouping : IGrouping<K, E> |
| 54 |
{ |
| 55 |
KeyValuePair<K, List<E>> kv; |
| 56 |
|
| 57 |
public Grouping(KeyValuePair<K, List<E>> kv) |
| 58 |
{ |
| 59 |
this.kv = kv; |
| 60 |
} |
| 61 |
|
| 62 |
public K Key |
| 63 |
{ |
| 64 |
get { return kv.Key; } |
| 65 |
} |
| 66 |
|
| 67 |
public IEnumerator<E> GetEnumerator() |
| 68 |
{ |
| 69 |
return kv.Value.GetEnumerator(); |
| 70 |
} |
| 71 |
|
| 72 |
Collections.IEnumerator Collections.IEnumerable.GetEnumerator() |
| 73 |
{ |
| 74 |
return GetEnumerator(); |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
Collections.IEnumerator Collections.IEnumerable.GetEnumerator() |
| 79 |
{ |
| 80 |
return GetEnumerator(); |
| 81 |
} |
| 82 |
} |
| 83 |
} |