This is it
This is it

Reputation: 789

Something like IDictionary<TKey, TValue>, but only for keys (value is not needed) in .NET?

Is there something in .Net that allows storing/retrieving/contains keys without values?
I can use Dictionary<string, string> and always store String.Empty as value, but maybe there is some better solution?

Upvotes: 3

Views: 139

Answers (5)

David M&#229;rtensson
David M&#229;rtensson

Reputation: 7600

List<T> has a Contains method to test if a certain element exists in the list but HashSet as other suggests would work and is probably faster as it cannot contain duplicates. List<T> can have duplicate values.

Upvotes: 0

gsharp
gsharp

Reputation: 27927

If you are using .NET 3.5 you can go with the HashSet class. If not then you have to create your own generic class (maybe inherit from List<> and do the checks).

Upvotes: 1

MrKWatkins
MrKWatkins

Reputation: 2658

Try Hashset<T> if you're using .NET 3.5 or above.

Upvotes: 3

casperOne
casperOne

Reputation: 74530

You can use the HashSet<T> class, it's meant to store distinct values in a set.

The main difference between that and an IDictionary{TKey, TValue} (aside from the fact that it doesn't store values) is that you can add the same value to the HashSet<T> and if it already exists it does not throw an exception (when you try and call the Add method on it, as opposed to the Add method on IDictionary{TKey, TValue}, which will throw an ArgumentException if the item exists in the dictionary already.

Upvotes: 11

Doctor Jones
Doctor Jones

Reputation: 21654

You're probably looking for System.Collections.Generic.HashSet<T>

Here's the relevant excerpt from MSDN:

The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

The capacity of a HashSet<T> object is the number of elements that the object can hold. A HashSet<T> object's capacity automatically increases as elements are added to the object.

Starting with the .NET Framework version 4, the HashSet<T> class implements the ISet<T> interface.

Upvotes: 1

Related Questions