mirror of
https://github.com/Alex-Rachel/TEngine.git
synced 2025-08-07 16:45:10 +00:00
141 lines
3.2 KiB
C#
141 lines
3.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace ET
|
|
{
|
|
public class MultiMap<T, K>:
|
|
//#if UNITY
|
|
// SortedLinkList<T, List<K>>
|
|
//#else
|
|
SortedDictionary<T, List<K>>
|
|
//#endif
|
|
{
|
|
private readonly List<K> Empty = new();
|
|
private readonly int maxPoolCount;
|
|
private readonly Queue<List<K>> pool;
|
|
|
|
public MultiMap(int maxPoolCount = 0)
|
|
{
|
|
this.maxPoolCount = maxPoolCount;
|
|
this.pool = new Queue<List<K>>(maxPoolCount);
|
|
}
|
|
|
|
private List<K> FetchList()
|
|
{
|
|
if (this.pool.Count > 0)
|
|
{
|
|
return this.pool.Dequeue();
|
|
}
|
|
return new List<K>(10);
|
|
}
|
|
|
|
private void Recycle(List<K> list)
|
|
{
|
|
if (list == null)
|
|
{
|
|
return;
|
|
}
|
|
if (this.pool.Count == this.maxPoolCount)
|
|
{
|
|
return;
|
|
}
|
|
list.Clear();
|
|
this.pool.Enqueue(list);
|
|
}
|
|
|
|
public void Add(T t, K k)
|
|
{
|
|
List<K> list;
|
|
this.TryGetValue(t, out list);
|
|
if (list == null)
|
|
{
|
|
list = this.FetchList();
|
|
this.Add(t, list);
|
|
}
|
|
list.Add(k);
|
|
}
|
|
|
|
public bool Remove(T t, K k)
|
|
{
|
|
List<K> list;
|
|
this.TryGetValue(t, out list);
|
|
if (list == null)
|
|
{
|
|
return false;
|
|
}
|
|
if (!list.Remove(k))
|
|
{
|
|
return false;
|
|
}
|
|
if (list.Count == 0)
|
|
{
|
|
this.Remove(t);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public new bool Remove(T t)
|
|
{
|
|
List<K> list;
|
|
this.TryGetValue(t, out list);
|
|
if (list == null)
|
|
{
|
|
return false;
|
|
}
|
|
this.Recycle(list);
|
|
return base.Remove(t);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 不返回内部的list,copy一份出来
|
|
/// </summary>
|
|
/// <param name="t"></param>
|
|
/// <returns></returns>
|
|
public K[] GetAll(T t)
|
|
{
|
|
List<K> list;
|
|
this.TryGetValue(t, out list);
|
|
if (list == null)
|
|
{
|
|
return Array.Empty<K>();
|
|
}
|
|
return list.ToArray();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 返回内部的list
|
|
/// </summary>
|
|
/// <param name="t"></param>
|
|
/// <returns></returns>
|
|
public new List<K> this[T t]
|
|
{
|
|
get
|
|
{
|
|
this.TryGetValue(t, out List<K> list);
|
|
return list ?? Empty;
|
|
}
|
|
}
|
|
|
|
public K GetOne(T t)
|
|
{
|
|
List<K> list;
|
|
this.TryGetValue(t, out list);
|
|
if (list != null && list.Count > 0)
|
|
{
|
|
return list[0];
|
|
}
|
|
return default;
|
|
}
|
|
|
|
public bool Contains(T t, K k)
|
|
{
|
|
List<K> list;
|
|
this.TryGetValue(t, out list);
|
|
if (list == null)
|
|
{
|
|
return false;
|
|
}
|
|
return list.Contains(k);
|
|
}
|
|
}
|
|
} |