82 lines
No EOL
1.9 KiB
C#
82 lines
No EOL
1.9 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using JD.Collections.Extensions;
|
|
|
|
namespace JD.Collections
|
|
{
|
|
/// <summary>
|
|
/// A set that enumerates its elements in the order they are added.
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public class OrderedSet<T> : ICollection<T>
|
|
{
|
|
#region Variables
|
|
|
|
private readonly Dictionary<T, LinkedListNode<T>> m_itemsIndex = new Dictionary<T, LinkedListNode<T>>();
|
|
private readonly LinkedList<T> m_orderedItems = new LinkedList<T>();
|
|
|
|
#endregion
|
|
|
|
#region ICollection implementation
|
|
|
|
public IEnumerator<T> GetEnumerator()
|
|
{
|
|
return m_orderedItems.GetEnumerator();
|
|
}
|
|
|
|
IEnumerator IEnumerable.GetEnumerator()
|
|
{
|
|
return GetEnumerator();
|
|
}
|
|
|
|
public void Add(T item)
|
|
{
|
|
if (!m_itemsIndex.ContainsKey(item))
|
|
{
|
|
LinkedListNode<T> node = m_orderedItems.AddLast(item);
|
|
m_itemsIndex.Add(item, node);
|
|
}
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
m_itemsIndex.Clear();
|
|
m_orderedItems.Clear();
|
|
}
|
|
|
|
public bool Contains(T item)
|
|
{
|
|
return m_itemsIndex.ContainsKey(item);
|
|
}
|
|
|
|
public void CopyTo(T[] array, int arrayIndex)
|
|
{
|
|
this.AsEnumerable().CopyTo(array, arrayIndex);
|
|
}
|
|
|
|
public bool Remove(T item)
|
|
{
|
|
LinkedListNode<T> node;
|
|
if (m_itemsIndex.TryGetValue(item, out node))
|
|
{
|
|
m_itemsIndex.Remove(item);
|
|
m_orderedItems.Remove(node);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public int Count
|
|
{
|
|
get { return m_orderedItems.Count; }
|
|
}
|
|
|
|
public bool IsReadOnly
|
|
{
|
|
get { return false; }
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
} |