Does anyone know if there is a good equivalent to Java's Set
collection in C#? I know that you can somewhat mimic a set using a Dictionary
or a HashTable
by populating but ignoring the values, but that's not a very elegant way.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I use a wrapper around a
Dictionary<T, object>
, storing nulls in the values. This gives O(1) add, lookup and remove on the keys, and to all intents and purposes acts like a set.Try HashSet:
As others have mentioned, there doesn't appear to be a set implementation in the .NET standard with set semantics.
See this question for why
HashSet
isn't always desired as a set implementation.If you're interested in rolling your own set class, here's one simple approach:
Example usage:
If you're using .NET 4.0 or later:
In the case where you need sorting then use
SortedSet<T>
. Otherwise if you don't, then useHashSet<T>
since it'sO(1)
for search and manipulate operations. WhereasSortedSet<T>
isO(log n)
for search and manipulate operations.