Is there something in .Net that allows storing/retrieving/contains keys without values?
I can useDictionary<string, string>
and always store String.Empty
as value, but maybe there is some 开发者_如何学Cbetter solution?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.
Try Hashset<T>
if you're using .NET 3.5 or above.
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.
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).
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.
精彩评论