A simple Set collection
In a Microsoft internal discussion, someone asked for Set functionality in a collection. I threw this together.
What do you think? Useful or no?
using System.Collections.Generic;
using System.Diagnostics;
class Set<TItem>
{
Dictionary<TItem, bool> _list = new Dictionary<TItem, bool>();
public bool Contains(TItem item) { return _list.ContainsKey(item); }
public void Add(TItem item)
{
if (!Contains(item))
{
this._list.Add(item, false);
}
}
public void Remove(TItem item)
{
if (!Contains(item))
{
// TODO: pick a better exception type
throw new System.Exception();
}
this._list.Remove(item);
}
public int Count { get { return this._list.Count; } }
}
class Test
{
static void Main(string[] args)
{
Set<int> set = new Set<int>();
Debug.Assert(set.Count == 0);
Debug.Assert(set.Contains(1) == false);
set.Add(1);
Debug.Assert(set.Count == 1);
Debug.Assert(set.Contains(1) == true);
Debug.Assert(set.Contains(2) == false);
set.Add(1);
Debug.Assert(set.Count == 1);
Debug.Assert(set.Contains(1) == true);
Debug.Assert(set.Contains(2) == false);
set.Add(2);
Debug.Assert(set.Count == 2);
Debug.Assert(set.Contains(1) == true);
Debug.Assert(set.Contains(2) == true);
set.Remove(1);
Debug.Assert(set.Count == 1);
Debug.Assert(set.Contains(1) == false);
Debug.Assert(set.Contains(2) == true);
}
}