HashSet replacement in C# 2.0
I using List<T>
in my project, this list contains hundreds of entries. I am using List.Contains method quite a lot and this is hurting performance, I replaced the List with dictionary but it resulted in memory bottleneck, thus made performance even worst. Is there 开发者_StackOverflow中文版a better solution that one can suggest for searching in List? Is there a replacement of HashSet<T>
in C# 2.0 or some other way that is better both memory and speed wise?
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();
}
}
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.
精彩评论