有人知道c#中是否有类似于Java的Set集合的好方法吗?我知道您可以使用Dictionary或HashTable来填充但忽略值,从而在某种程度上模拟一个集合,但这不是一种非常优雅的方式。
当前回答
尝试HashSet:
The HashSet(Of 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(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object. The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary(Of TKey, TValue) or Hashtable collections. In simple terms, the HashSet(Of T) class can be thought of as a Dictionary(Of TKey, TValue) collection without values. A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...
其他回答
尝试HashSet:
The HashSet(Of 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(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object. The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary(Of TKey, TValue) or Hashtable collections. In simple terms, the HashSet(Of T) class can be thought of as a Dictionary(Of TKey, TValue) collection without values. A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...
如果你使用。net 4.0或更高版本:
在需要排序的情况下,使用SortedSet<T>。否则,如果没有,则使用HashSet<T>,因为它是O(1)用于搜索和操作操作。而SortedSet<T>对于搜索和操作操作是O(log n)。
在CodePlex上看看PowerCollections。除了Set和OrderedSet,它还有一些其他有用的集合类型,如Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary和OrderedMultiDictionary。
对于更多的集合,还有C5通用集合库。
我知道这是一个旧线程,但我遇到了同样的问题,发现HashSet非常不可靠,因为给定相同的种子,GetHashCode()返回不同的代码。我想,为什么不用List隐藏add方法呢
public class UniqueList<T> : List<T>
{
public new void Add(T obj)
{
if(!Contains(obj))
{
base.Add(obj);
}
}
}
因为List仅使用Equals方法来确定相等性,所以可以在T类型上定义Equals方法,以确保获得所需的结果。
我使用Dictionary<T对象>的包装器,在值中存储空值。这就提供了O(1)键的添加、查找和删除,并且在所有意图和目的上都像一个集合。
推荐文章
- 如何在JavaScript中映射/减少/过滤一个集?
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- AutoMapper:“忽略剩下的?”
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接
- 如何使用。net 4运行时运行PowerShell ?
- 在foreach循环中编辑字典值