using System.Collections.Generic;
using System.Linq;
///接口容器
public class UnOrderMultiMap
{
private readonly Dictionary> dictionary = new Dictionary>();
// 重用list
private readonly Queue> queue = new Queue>();
public Dictionary> GetDictionary()
{
return dictionary;
}
public void Add(T t, K k)
{
List list;
this.dictionary.TryGetValue(t, out list);
if (list == null)
{
list = FetchList();
dictionary[t] = list;
}
list.Add(k);
}
public KeyValuePair> First()
{
return dictionary.First();
}
public int Count
{
get
{
return dictionary.Count;
}
}
private List FetchList()
{
if (queue.Count > 0)
{
List list = queue.Dequeue();
list.Clear();
return list;
}
return new List();
}
private void RecycleList(List list)
{
// 防止暴涨
if (queue.Count > 100)
{
return;
}
list.Clear();
queue.Enqueue(list);
}
public bool Remove(T t, K k)
{
List list;
dictionary.TryGetValue(t, out list);
if (list == null)
{
return false;
}
if (!list.Remove(k))
{
return false;
}
if (list.Count == 0)
{
RecycleList(list);
dictionary.Remove(t);
}
return true;
}
public bool Remove(T t)
{
List list = null;
dictionary.TryGetValue(t, out list);
if (list != null)
{
RecycleList(list);
}
return dictionary.Remove(t);
}
/// 不返回内部的list,copy一份出来
public K[] GetAll(T t)
{
List list;
dictionary.TryGetValue(t, out list);
if (list == null)
{
return new K[0];
}
return list.ToArray();
}
/// 返回内部的list
public List this[T t]
{
get
{
List list;
dictionary.TryGetValue(t, out list);
return list;
}
}
public K GetOne(T t)
{
List list;
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;
dictionary.TryGetValue(t, out list);
if (list == null)
{
return false;
}
return list.Contains(k);
}
public bool ContainsKey(T t)
{
return dictionary.ContainsKey(t);
}
public void Clear()
{
foreach (KeyValuePair> keyValuePair in dictionary)
{
RecycleList(keyValuePair.Value);
}
dictionary.Clear();
}
}