using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace System.Linq { public class Lookup : ILookup { Dictionary> _groupings; internal static Lookup Create ( IEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer) { if (source == null) throw new ArgumentNullException ("source"); if (keySelector == null) throw new ArgumentNullException ("keySelector"); if (elementSelector == null) throw new ArgumentNullException ("elementSelector"); var lookup = new Lookup (comparer ?? EqualityComparer.Default); foreach (TSource element in source) { TKey key = keySelector (element); Grouping grouping; if (!lookup._groupings.TryGetValue (key, out grouping)) lookup._groupings.Add (key, grouping = new Grouping (key)); grouping.InnerList.Add (elementSelector (element)); } return lookup; } Lookup (IEqualityComparer comparer) { _groupings = new Dictionary> (comparer); } public int Count { get { return _groupings.Count; } } public IEnumerable this [TKey key] { get { Grouping result; if (_groupings.TryGetValue (key, out result)) return result; else return Enumerable.Empty (); } } public bool Contains (TKey key) { return _groupings.ContainsKey (key); } public IEnumerator> GetEnumerator () { foreach (var grouping in _groupings.Values) yield return grouping; } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } } }