我需要一个保留插入顺序的哈希集,框架中是否有这种实现
标准.NETHashSet
不保留插入顺序。
对于简单的测试,插入顺序可能会因为意外而保留,但不能保证,也不能总是这样。证明在两者之间进行一些删除就足够了
有关这方面的更多信息,请参见此问题:HashSet是否保留插入顺序
我已经简单地实现了一个HashSet
,它保证了插入顺序。它使用字典
查找项目,并使用链接列表
保持顺序。所有三个插入、删除和查找操作仍在O(1)中进行
公共类OrderedSet<;T>;:i收集<;T>;
{
专用只读IDictionary<;T,LinkedListNode<;T>;>;m\U字典;
私有只读链接列表<;T>;m\U链接列表;
公共OrderedSet()
:此(EqualityComparer<;T>;默认值)
{
}
公共订单集(IEqualityComparer<;T>;comparer)
{
m_Dictionary=newdictionary<;T,LinkedListNode<;T>;;(比较器);
m_LinkedList=新LinkedList<;T>;();
}
public int Count=>;m_Dictionary.Count;
公共虚拟bool IsReadOnly=>;m_Dictionary.IsReadOnly;
作废ICollection<;T>;。添加(T项)
{
增加(项目);
}
公共布尔添加(T项)
{
if(m_Dictionary.ContainsKey(item))返回false;
var node=m_LinkedList.AddLast(项目);
m_Dictionary.Add(项,节点);
返回true;
}
公共空间清除()
{
m_LinkedList.Clear();
m_Dictionary.Clear();
}
公共布尔删除(T项)
{
如果(item==null)返回false;
var found=m_Dictionary.TryGetValue(项,out var节点);
如果(!found)返回false;
m_字典。删除(项);
m_LinkedList.Remove(节点);
返回true;
}
公共IEnumerator<;T>;GetEnumerator()
{
返回m_LinkedList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
返回GetEnumerator();
}
公共布尔包含(T项)
{
返回项!=空&;m_字典.ContainsKey(项);
}
public void CopyTo(T[]数组,int arrayIndex)
{
m_LinkedList.CopyTo(数组、数组索引);
}
}