5 // Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
7 // Copyright (c) 2010 Jérémie "Garuma" Laval
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 using System.Threading;
30 using System.Collections;
31 using System.Collections.Generic;
32 using System.Collections.Concurrent;
34 namespace System.Linq.Parallel
36 internal class ConcurrentLookup<TKey, TElement> : ILookup<TKey, TElement>
38 ConcurrentDictionary<TKey, IEnumerable<TElement>> dictionary;
44 internal AddSlot (TElement element)
46 this.element = element;
49 internal IEnumerable<TElement> AddMethod (TKey key)
51 List<TElement> list = new List<TElement> ();
57 internal IEnumerable<TElement> UpdateMethod (TKey key, IEnumerable<TElement> old)
59 ICollection<TElement> coll = (ICollection<TElement>)old;
66 internal ConcurrentLookup (IEqualityComparer<TKey> comparer)
68 this.dictionary = new ConcurrentDictionary<TKey, IEnumerable<TElement>> (comparer);
71 internal void Add (TKey key, TElement element)
73 AddSlot slot = new AddSlot (element);
74 dictionary.AddOrUpdate (key, slot.AddMethod, slot.UpdateMethod);
77 public bool Contains (TKey key)
79 return dictionary.ContainsKey (key);
82 public IEnumerable<TElement> this[TKey key] {
84 return dictionary[key];
90 return dictionary.Count;
94 public IList<TKey> Keys {
96 return (IList<TKey>)dictionary.Keys;
100 IEnumerator IEnumerable.GetEnumerator ()
102 return (IEnumerator)GetEnumeratorInternal ();
105 IEnumerator<IGrouping<TKey, TElement>> IEnumerable<IGrouping<TKey, TElement>>.GetEnumerator ()
107 return GetEnumeratorInternal ();
110 IEnumerator<IGrouping<TKey, TElement>> GetEnumeratorInternal ()
112 return (IEnumerator<System.Linq.IGrouping<TKey,TElement>>) dictionary.Select ((pair) => new ConcurrentGrouping<TKey, TElement> (pair.Key, pair.Value)).GetEnumerator ();