Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet replacement in C# 2.0

Tags:

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 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?

like image 552
FIre Panda Avatar asked May 12 '11 12:05

FIre Panda


People also ask

What is new HashSet in C#?

In C#, HashSet is an unordered collection of unique elements. This collection is introduced in . NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.

Is HashSet sorted C#?

A HashSet<T> collection is not sorted and cannot contain duplicate elements.

Why do we use HashSet in C#?

Since HashSet contains only unique elements, its internal structure is optimized for faster searches. Note that you can store a single null value in a HashSet. So, HashSet is a good choice when you want a collection that contains unique elements and the elements in the collection can be searched quickly.


1 Answers

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>.

like image 70
Tergiver Avatar answered Oct 26 '22 19:10

Tergiver