using System.Collections.Generic; using System.Linq; namespace Model { public class MultiMap { private readonly SortedDictionary> dictionary = new SortedDictionary>(); // 重用list private readonly Queue> queue = new Queue>(); public SortedDictionary> GetDictionary() { return this.dictionary; } public void Add(T t, K k) { List list; this.dictionary.TryGetValue(t, out list); if (list == null) { list = this.FetchList(); } list.Add(k); this.dictionary[t] = list; } public KeyValuePair> First() { return this.dictionary.First(); } public int Count { get { return this.dictionary.Count; } } private List FetchList() { if (this.queue.Count > 0) { List list = this.queue.Dequeue(); list.Clear(); return list; } return new List(); } private void RecycleList(List list) { // 防止暴涨 if (this.queue.Count > 100) { return; } list.Clear(); this.queue.Enqueue(list); } public bool Remove(T t, K k) { List 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) { List 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) { List list; this.dictionary.TryGetValue(t, out list); if (list == null) { return new K[0]; } return list.ToArray(); } /// /// 返回内部的list /// /// /// public List this[T t] { get { List list; this.dictionary.TryGetValue(t, out list); return list; } } public K GetOne(T t) { List list; this.dictionary.TryGetValue(t, out list); if (list != null && list.Count > 0) { return list[0]; } return default(K); } public bool Contains(T t, K k) { List list; this.dictionary.TryGetValue(t, out list); if (list == null) { return false; } return list.Contains(k); } } }