推荐的.NET类用于唯一整数的集合吗?

时间:2020-03-06 15:02:27  来源:igfitidea点击:

对于需要保留唯一整数列表的类,我们会推荐什么?

我将要向集合中添加()整数,并检查是否存在,例如Contains()。

也可以将它们作为字符串显示在列表中,例如。 " 1、5、10、21"。

解决方案

哈希集:

The HashSet<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<T> object is the number of elements that the object can hold. A HashSet<T> object's capacity automatically increases as elements are added to the object.
  
  The HashSet<T> class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey,?TValue> or Hashtable collections. In simple terms, the HashSet<T> class can be thought of as a Dictionary<TKey,?TValue> collection without values.
  
  A HashSet<T> collection is not sorted and cannot contain duplicate elements...

如果不能使用.NET 3.5,则不能使用HashSet。如果是这样,我们可以根据Dictionary结构轻松滚动自己的页面。

public class Set<T> {
    private class Unit { ... no behavior }
    private Dictionary<T, Unit> d;

....
}

单位旨在为一种仅具有一个值的类型。将元素映射到什么都无所谓,只需使用键即可知道集合中的内容。我们在问题中要求的操作很容易实现。

我们可以从KeyedCollection继承一个类。这样,键可以是值本身,我们可以覆盖ToString以便获得所需的输出。这可能会给我们我们想要/需要的行为。

请注意,此答案适用于Q的框架2.0部分

在我的测试中,我发现在处理非常大的数据集(在我的情况下为100,000+)时,具有虚拟值的Dictionary比HashSet更快。我希望这是因为字典允许我们设置初始容量,但是我真的不知道。在我们描述的情况下,如果我期望有大量的数字,则可能会使用Dictionary,然后(或者根据意图将其添加到Dictionary中)使用字符串生成器对其进行迭代,创建输出字符串。