有人知道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...
如果你使用。net 3.5,你可以使用HashSet<T>。net确实不能像Java那样满足集合的需求。
Wintellect PowerCollections也可能有所帮助。
我用Iesi。集合http://www.codeproject.com/KB/recipes/sets.aspx
它被用在很多OSS项目中,我第一次接触它是在NHibernate中
在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方法,以确保获得所需的结果。
如果你使用。net 4.0或更高版本:
在需要排序的情况下,使用SortedSet<T>。否则,如果没有,则使用HashSet<T>,因为它是O(1)用于搜索和操作操作。而SortedSet<T>对于搜索和操作操作是O(log n)。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本