Lookup<TKey, TElement>
sealed class Lookup<TKey, TElement> : ILookup<TKey, TElement>, IEnumerable<IGrouping<TKey, TElement>>, IEnumerable
Represents a collection of keys each mapped to one or more values.
using Newtonsoft.Json.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Newtonsoft.Json.Utilities.LinqBridge
{
internal sealed class Lookup<TKey, TElement> : ILookup<TKey, TElement>, IEnumerable<IGrouping<TKey, TElement>>, IEnumerable
{
private readonly Dictionary<TKey, IGrouping<TKey, TElement>> _map;
public int Count => _map.Count;
public IEnumerable<TElement> this[TKey key] {
get {
if (!_map.TryGetValue(key, out IGrouping<TKey, TElement> value))
return Enumerable.Empty<TElement>();
return value;
}
}
internal Lookup(IEqualityComparer<TKey> comparer)
{
_map = new Dictionary<TKey, IGrouping<TKey, TElement>>(comparer);
}
internal void Add(IGrouping<TKey, TElement> item)
{
_map.Add(item.Key, item);
}
internal IEnumerable<TElement> Find(TKey key)
{
if (!_map.TryGetValue(key, out IGrouping<TKey, TElement> value))
return null;
return value;
}
public bool Contains(TKey key)
{
return _map.ContainsKey(key);
}
public IEnumerable<TResult> ApplyResultSelector<TResult>(Newtonsoft.Json.Serialization.Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
{
if (resultSelector == null)
throw new ArgumentNullException("resultSelector");
Dictionary<TKey, IGrouping<TKey, TElement>>.Enumerator enumerator = this._map.GetEnumerator();
try {
while (enumerator.MoveNext()) {
KeyValuePair<TKey, IGrouping<TKey, TElement>> current = enumerator.Current;
yield return resultSelector(current.Key, current.Value);
}
} finally {
((IDisposable)enumerator).Dispose();
}
enumerator = default(Dictionary<TKey, IGrouping<TKey, TElement>>.Enumerator);
}
public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
{
return _map.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}