using System.Collections.Generic; using System.Linq; namespace ETModel { public class MultiMapSet { private readonly SortedDictionary> dictionary = new SortedDictionary>(); // 重用list private static readonly Queue> queue = new Queue>(); private static HashSet Empty = new HashSet(); public SortedDictionary> GetDictionary() { return this.dictionary; } public void Add(T t, K k) { HashSet list; this.dictionary.TryGetValue(t, out list); if (list == null) { list = this.FetchList(); this.dictionary[t] = list; } list.Add(k); } public KeyValuePair> First() { return this.dictionary.First(); } public T FirstKey() { return this.dictionary.Keys.First(); } public int Count { get { return this.dictionary.Count; } } private HashSet FetchList() { if (queue.Count > 0) { HashSet list = queue.Dequeue(); list.Clear(); return list; } return new HashSet(); } private void RecycleList(HashSet list) { list.Clear(); queue.Enqueue(list); } public bool Remove(T t, K k) { HashSet list; this.dictionary.TryGetValue(t, out list); if (list == null) { return false; } if (!list.Remove(k)) { return false; } if (list.Count == 0) { this.RecycleList(list); this.dictionary.Remove(t); } return true; } public bool Remove(T t) { HashSet list = null; this.dictionary.TryGetValue(t, out list); if (list != null) { this.RecycleList(list); } return this.dictionary.Remove(t); } /// /// 不返回内部的list,copy一份出来 /// /// /// public K[] GetAll(T t) { HashSet list; this.dictionary.TryGetValue(t, out list); if (list == null) { return new K[0]; } return list.ToArray(); } /// /// 返回内部的list /// /// /// public HashSet this[T t] { get { this.dictionary.TryGetValue(t, out var list); return list ?? Empty; } } public K GetOne(T t) { HashSet list; this.dictionary.TryGetValue(t, out list); if (list != null && list.Count > 0) { return list.FirstOrDefault(); } return default(K); } public bool Contains(T t, K k) { HashSet list; this.dictionary.TryGetValue(t, out list); if (list == null) { return false; } return list.Contains(k); } public bool ContainsKey(T t) { return this.dictionary.ContainsKey(t); } public void Clear() { foreach (HashSet list in this.dictionary.Values) { list.Clear(); queue.Enqueue(list); } dictionary.Clear(); } } }