HashSet replacement in C# 2.0

∥☆過路亽.° 提交于 2019-12-01 16:29:05

A Dictionary<T,bool> can be used in place of a HashSet<T>. Whether you add items with a value of True or False is a coin toss, the value is not relevant.

It's more cumbersome than a HashSet<T>, and not quite a light-weight, but it's certainly better than a List<T>.

public class HashCollection <T> : ICollection <T>
{
    private Dictionary<T, bool> _innerDictionary;

    public HashCollection()
    {
        _innerDictionary = new Dictionary<T, bool>();
    }

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

    private void AddInternal(T item)
    {
        _innerDictionary.Add(item, false);
    }

    public bool Add(T item)
    {
        if (_innerDictionary.ContainsKey(item))
            return false;

        AddInternal(item);
        return true;
    }

    public void Clear()
    {
        _innerDictionary.Clear();
        _innerDictionary = new Dictionary<T, bool>();
    }

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

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

    public int Count
    {
        get { return _innerDictionary.Keys.Count; }
    }

    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public bool Remove(T item)
    {
        return _innerDictionary.Remove(item);
    }

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

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

If you can live withthe requirement that .Net 3.5 framework be installed, you can use the HashSet from .Net 3.5 (System.Core.dll) in a 2.0 project.

See this question: Using HashSet in C# 2.0, compatible with 3.5

If that's a no go, I would use dictionary instead.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!