有人知道c#中是否有类似于Java的Set集合的好方法吗?我知道您可以使用Dictionary或HashTable来填充但忽略值,从而在某种程度上模拟一个集合,但这不是一种非常优雅的方式。
当前回答
我知道这是一个旧线程,但我遇到了同样的问题,发现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方法,以确保获得所需的结果。
其他回答
尝试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通用集合库。
我使用Dictionary<T对象>的包装器,在值中存储空值。这就提供了O(1)键的添加、查找和删除,并且在所有意图和目的上都像一个集合。
推荐文章
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 不可变与不可修改的集合
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空