Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Hashtables/HashSets in .NET?

I have a list of ~9000 products, and some of which may have duplicates.

I wanted to make a HashTable of these products with the products serial number as their key so I can find duplicates easily.

How would one go about using a HashTable in C#/.NET? Would a HashSet be more appropriate?

Eventually I would like a list like:

Key-Serial: 11110 - Contains: Product1
Key-Serial: 11111 - Contains: Product3, Product6, Product7
Key-Serial: 11112 - Contains: Product4
Key-Serial: 11113 - Contains: Product8, Product9

So, I have a list of all products, and they are grouped by the ones that have duplicate serial numbers. What is the "correct" way to do this?

like image 731
Biro Avatar asked Jan 03 '10 18:01

Biro


2 Answers

I think Dictionary is the recommended class for stuff like this.

it would be something like this in your case

Dictionary<string, List<Product>>

(using serial string as key)

like image 119
peter p Avatar answered Oct 23 '22 14:10

peter p


A great option now available in .NET is the Lookup class. From the MSDN documentation:

A Lookup(Of TKey, TElement) resembles a Dictionary(Of TKey, TValue). The difference is that a Dictionary(Of TKey, TValue) maps keys to single values, whereas a Lookup(Of TKey, TElement) maps keys to collections of values.

There are some differences between a Lookup and Dictionary(Of List). Namely, the Lookup is immutable (can't add or remove elements or keys after it's created). Depending on how you plan to use your data, the Lookup may be advantageous compared to GroupBy().

like image 41
Zairja Avatar answered Oct 23 '22 14:10

Zairja