Skip to content

Instantly share code, notes, and snippets.

@fuzzblob
Created July 11, 2018 16:41
Show Gist options
  • Save fuzzblob/4b4aa926c5cf7ebfc07524373283b194 to your computer and use it in GitHub Desktop.
Save fuzzblob/4b4aa926c5cf7ebfc07524373283b194 to your computer and use it in GitHub Desktop.
A data structure with fast Conains check (through HashSet<T>) that also allows fast iteration (through List<T>)
using System.Collections.Generic;
public class HashedList<T>
{
private List<T> _list;
private HashSet<T> _set;
public List<T> Elements { get { return _list; } }
public T this[int i]
{
get
{
if(i < Count)
return _list[i];
return null;
}
set
{
if(i < Count)
_list[i] = value;
}
}
public int Count { get { return _list.Count; } }
public HashedList()
{
_list = new List<T>();
_set = new HashSet<T>();
}
public HashedList(int initialCapacity)
{
_list = new List<T>(initialCapacity);
_set = new HashSet<T>();
}
public bool Contains(T obj)
{
return _set.Contains(obj);
}
public bool Add(T obj)
{
if (_set.Add(obj) == false)
return false;
_list.Add(obj);
return true;
}
public bool Remove(T obj)
{
if (_set.Remove(obj) == false)
return false;
return _list.Remove(obj);
}
public bool RemoveAt(int index)
{
if(Count > index
&& _list[index] != null)
{
T obj = _list[index];
_list.RemoveAt(index);
_set.Remove(obj);
return true;
}
return false;
}
public void CopyTo(ref T[] array)
{
_list.CopyTo(array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment