Replacing HashSet in C # 2.0

I use List<T> in my project, this list contains hundreds of records. I use the List.Contains method quite a lot, and this affects the performance, I replaced the list dictionary, but this led to a lack of memory, which made the performance even the worst. Is there a better solution you can offer for searching a List? Is there a replacement for HashSet<T> with C # 2.0 or some other way that is better for both memory and speed?

+7
source share
3 answers

A Dictionary<T,bool> can be used instead of HashSet<T> . If you add elements with the value True or False, this is a coin toss; the value does not matter.

This is more cumbersome than a HashSet<T> , and not quite easy, but it is certainly better than a List<T> .

+6
source
 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(); } } 
+3
source

If you can live with the requirement to install the .Net 3.5 infrastructure, you can use the HashSet from .Net 3.5 (System.Core.dll) in project 2.0.

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

If it is not, I would use a dictionary instead.

0
source

All Articles