有人知道c#中是否有类似于Java的Set集合的好方法吗?我知道您可以使用Dictionary或HashTable来填充但忽略值,从而在某种程度上模拟一个集合,但这不是一种非常优雅的方式。
当前回答
我用Iesi。集合http://www.codeproject.com/KB/recipes/sets.aspx
它被用在很多OSS项目中,我第一次接触它是在NHibernate中
其他回答
尝试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...
我使用Dictionary<T对象>的包装器,在值中存储空值。这就提供了O(1)键的添加、查找和删除,并且在所有意图和目的上都像一个集合。
如果你使用。net 3.5,你可以使用HashSet<T>。net确实不能像Java那样满足集合的需求。
Wintellect PowerCollections也可能有所帮助。
我知道这是一个旧线程,但我遇到了同样的问题,发现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方法,以确保获得所需的结果。
在CodePlex上看看PowerCollections。除了Set和OrderedSet,它还有一些其他有用的集合类型,如Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary和OrderedMultiDictionary。
对于更多的集合,还有C5通用集合库。
推荐文章
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和
- 我如何使用IValidatableObject?
- 如何指定最小值,但没有使用范围数据注释属性的最大小数?
- 如何在PowerShell中获得本地主机名?
- c# vs Java Enum(适合c#新手)
- c#消毒文件名
- 为什么在Java和。net中不能修改字符串?
- 在EF中更新父实体时如何添加/更新子实体
- ASP。NET身份的默认密码散列器-它是如何工作的,它是安全的?
- 如何写一个JSON文件在c# ?