LinkedHashSet (追加順序を保持するSet)

[LinkedHashMapを書いた](http://qiita.com/matarillo/items/c09e0f3e5a61f84a51e2)んだから[LinkedHashSet](http://docs.oracle.com/javase/jp/8/docs/api/java/util/LinkedHashSet.html)もついでに。

（追記）こっちの内部実装も`List<T>`版を書いてみた。要素の削除が発生したら遅くなると思われるので、集合演算をしないのであれば速いのかもしれない。

```csharp:LinkedHashSet.cs
/*
The MIT License (MIT)

Copyright (c) 2015 matarillo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

using System;
using System.Collections.Generic;

public class LinkedHashSet<T> : ISet<T>
{
    private readonly Dictionary<T, int> table; // T -> int
    private readonly List<T> list;             // int -> T

    public LinkedHashSet()
    {
        table = new Dictionary<T, int>();
        list = new List<T>();
    }

    public LinkedHashSet(IEnumerable<T> collection)
    {
        var countable = collection as ICollection<T>;
        if (countable != null)
        {
            table = new Dictionary<T, int>(countable.Count);
            list = new List<T>(countable.Count);
        }
        else
        {
            table = new Dictionary<T, int>();
            list = new List<T>();
        }
        UnionWith(collection);
    }

    public LinkedHashSet(IEqualityComparer<T> comparer)
    {
        table = new Dictionary<T, int>(comparer);
        list = new List<T>();
    }

    public LinkedHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
    {
        var countable = collection as ICollection<T>;
        if (countable != null)
        {
            table = new Dictionary<T, int>(countable.Count, comparer);
            list = new List<T>(countable.Count);
        }
        else
        {
            table = new Dictionary<T, int>(comparer);
            list = new List<T>();
        }
        UnionWith(collection);
    }

    public LinkedHashSet(int capacity, IEqualityComparer<T> comparer)
    {
        table = new Dictionary<T, int>(capacity, comparer);
        list = new List<T>(capacity);
    }

    public IEqualityComparer<T> Comparer
    {
        get { return table.Comparer; }
    }

    public bool Add(T item)
    {
        if (table.ContainsKey(item))
        {
            return false;
        }
        list.Add(item);
        table.Add(item, list.Count - 1);
        return true;
    }

    private void EnsureNotNull(IEnumerable<T> other)
    {
        if (other == null) throw new ArgumentNullException("other");
    }

    public void ExceptWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        foreach (var item in other) Remove(item);
    }

    public void IntersectWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        var intersect = Intersect(other);
        for (var i = 0; i < list.Count; )
        {
            var value = list[i];
            if (intersect.Contains(value))
            {
                table[value] = i;
                i++;
            }
            else
            {
                table.Remove(value);
                list.RemoveAt(i);
                // listから要素を削除したので、iは動かさない
            }
        }
    }
    private HashSet<T> Intersect(IEnumerable<T> other)
    {
        var intersect = new HashSet<T>();
        foreach (var item in other)
            if (table.ContainsKey(item))
                intersect.Add(item);
        return intersect;
    }

    public bool IsProperSubsetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsProperSubsetOf(other);
    }

    public bool IsProperSupersetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsProperSupersetOf(other);
    }

    public bool IsSubsetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsSubsetOf(other);
    }

    public bool IsSupersetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsSupersetOf(other);
    }

    public bool Overlaps(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).Overlaps(other);
    }

    public bool SetEquals(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).SetEquals(other);
    }

    public void SymmetricExceptWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        var intersect = AddAndIntersect(other);
        for (var i = 0; i < list.Count; )
        {
            var value = list[i];
            if (intersect.Contains(value))
            {
                table.Remove(value);
                list.RemoveAt(i);
                // listから要素を削除したので、iは動かさない
            }
            else
            {
                table[value] = i;
                i++;
            }
        }
    }

    private HashSet<T> AddAndIntersect(IEnumerable<T> other)
    {
        var intersect = new HashSet<T>();
        foreach (var item in other)
            if (!Add(item))
                intersect.Add(item);
        return intersect;
    }

    public void UnionWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        foreach (var item in other) Add(item);
    }

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

    public void Clear()
    {
        table.Clear();
        list.Clear();
    }

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

    public void CopyTo(T[] array, int arrayIndex)
    {
        list.CopyTo(array, arrayIndex);
    }

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

    public bool IsReadOnly
    {
        get { return false; }
    }

    public bool Remove(T item)
    {
        int index;
        if (table.TryGetValue(item, out index))
        {
            table.Remove(item);
            list.RemoveAt(index);
            for (var i = index; i < list.Count; i++)
            {
                table[list[i]] = i;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

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

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}
```

以下は最初の実装、`LinkedList<T>`版。

```csharp:LinkedHashSet.cs
/*
The MIT License (MIT)

Copyright (c) 2015 matarillo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

using System;
using System.Collections.Generic;

public class LinkedHashSet<T> : ISet<T>
{
    private readonly Dictionary<T, LinkedListNode<T>> table;
    private readonly LinkedList<T> list;

    public LinkedHashSet()
    {
        table = new Dictionary<T, LinkedListNode<T>>();
        list = new LinkedList<T>();
    }

    public LinkedHashSet(IEnumerable<T> collection)
    {
        var countable = collection as ICollection<T>;
        table = (countable != null)
            ? new Dictionary<T, LinkedListNode<T>>(countable.Count)
            : new Dictionary<T, LinkedListNode<T>>();
        list = new LinkedList<T>();
        UnionWith(collection);
    }

    public LinkedHashSet(IEqualityComparer<T> comparer)
    {
        table = new Dictionary<T, LinkedListNode<T>>(comparer);
        list = new LinkedList<T>();
    }

    public LinkedHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
    {
        var countable = collection as ICollection<T>;
        table = (countable != null)
            ? new Dictionary<T, LinkedListNode<T>>(countable.Count, comparer)
            : new Dictionary<T, LinkedListNode<T>>(comparer);
        list = new LinkedList<T>();
        UnionWith(collection);
    }

    public LinkedHashSet(int capacity, IEqualityComparer<T> comparer)
    {
        table = new Dictionary<T, LinkedListNode<T>>(capacity, comparer);
        list = new LinkedList<T>();
    }

    public IEqualityComparer<T> Comparer
    {
        get { return table.Comparer; }
    }

    public bool Add(T item)
    {
        if (table.ContainsKey(item))
        {
            return false;
        }
        table.Add(item, list.AddLast(item));
        return true;
    }

    private void EnsureNotNull(IEnumerable<T> other)
    {
        if (other == null) throw new ArgumentNullException("other");
    }

    public void ExceptWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        foreach (var item in other) Remove(item);
    }

    public void IntersectWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        var intersect = Intersect(other);
        for (var n = list.First; n != null; )
        {
            if (intersect.Contains(n.Value))
            {
                n = n.Next;
            }
            else
            {
                n = RemoveAndNext(n);
            }
        }
    }
    private HashSet<T> Intersect(IEnumerable<T> other)
    {
        var intersect = new HashSet<T>();
        foreach (var item in other)
            if (table.ContainsKey(item))
                intersect.Add(item);
        return intersect;
    }

    public bool IsProperSubsetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsProperSubsetOf(other);
    }

    public bool IsProperSupersetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsProperSupersetOf(other);
    }

    public bool IsSubsetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsSubsetOf(other);
    }

    public bool IsSupersetOf(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).IsSupersetOf(other);
    }

    public bool Overlaps(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).Overlaps(other);
    }

    public bool SetEquals(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        return new HashSet<T>(list).SetEquals(other);
    }

    public void SymmetricExceptWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        var intersect = AddAndIntersect(other);
        for (var n = list.First; n != null; )
        {
            if (intersect.Contains(n.Value))
            {
                n = RemoveAndNext(n);
            }
            else
            {
                n = n.Next;
            }
        }
    }

    private HashSet<T> AddAndIntersect(IEnumerable<T> other)
    {
        var intersect = new HashSet<T>();
        foreach (var item in other)
            if (!Add(item))
                intersect.Add(item);
        return intersect;
    }

    private LinkedListNode<T> RemoveAndNext(LinkedListNode<T> node)
    {
        var n = node.Next;
        table.Remove(node.Value);
        list.Remove(node);
        return n;
    }

    public void UnionWith(IEnumerable<T> other)
    {
        EnsureNotNull(other);
        foreach (var item in other) Add(item);
    }

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

    public void Clear()
    {
        table.Clear();
        list.Clear();
    }

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

    public void CopyTo(T[] array, int arrayIndex)
    {
        list.CopyTo(array, arrayIndex);
    }

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

    public bool IsReadOnly
    {
        get { return false; }
    }

    public bool Remove(T item)
    {
        LinkedListNode<T> node = null;
        if (table.TryGetValue(item, out node))
        {
            table.Remove(item);
            list.Remove(node);
            return true;
        }
        else
        {
            return false;
        }
    }

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

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}
```