任何现有的 .Net 有序集?

J4N*_*J4N 4 .net c# collections list set

我正在寻找 .Net 类,它基本上将:

  • 确保项目在其中是唯一的(如 HashSet)
  • 确保当我们枚举时,我们以与插入它们相同的顺序获得项目(如列表)

是否有一个现有的 .Net 类可以做到这一点?

我知道HashSet(不保证顺序),SortedSet(内容的顺序),但它们不符合我的需要。我没有任何其他需求(例如 aStack或 a Queue)。

我目前的替代方法是拥有List<>并使用Contains(...)之前添加和删除数据。

小智 5

你是对的。HashSet 不保留插入顺序。

Stackoverflow:通过 achitaka-san 保留排序的 HashSet 它使用 Dictionary 查找项目,使用 LinkedList 保留顺序。所有三个插入、删除和查找仍然在 O(1) 中工作。

public class OrderedSet<T> : ICollection<T>
{
    private readonly IDictionary<T, LinkedListNode<T>> m_Dictionary;
    private readonly LinkedList<T> m_LinkedList;

    public OrderedSet()
        : this(EqualityComparer<T>.Default)
    {
    }

    public OrderedSet(IEqualityComparer<T> comparer)
    {
        m_Dictionary = new Dictionary<T, LinkedListNode<T>>(comparer);
        m_LinkedList = new LinkedList<T>();
    }

    public int Count
    {
        get { return m_Dictionary.Count; }
    }

    public virtual bool IsReadOnly
    {
        get { return m_Dictionary.IsReadOnly; }
    }

    void ICollection<T>.Add(T item)
    {
        Add(item);
    }

    public bool Add(T item)
    {
        if (m_Dictionary.ContainsKey(item)) return false;
        LinkedListNode<T> node = m_LinkedList.AddLast(item);
        m_Dictionary.Add(item, node);
        return true;
    }

    public void Clear()
    {
        m_LinkedList.Clear();
        m_Dictionary.Clear();
    }

    public bool Remove(T item)
    {
        LinkedListNode<T> node;
        bool found = m_Dictionary.TryGetValue(item, out node);
        if (!found) return false;
        m_Dictionary.Remove(item);
        m_LinkedList.Remove(node);
        return true;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return m_LinkedList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public bool Contains(T item)
    {
        return m_Dictionary.ContainsKey(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        m_LinkedList.CopyTo(array, arrayIndex);
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个实现:

@Codeproject:保留插入顺序的 HashSet 或 LinkedHashSet 的 .NET 实现