尝试向HashSet添加值不会更改其中的值

som*_*ing 6 c# hashset

我有一个HashSet当我使用Add该集合的方法时,没有添加任何内容.输出仍然2, 3, 5, 7, 11, 13是,输出.Count是6.

这是一个错误还是我在这里做错了什么?

namespace AllerDiz
{
    class MainClass
        {
            public static void Main (string[] args)
            {
                HashSet<int> smallPrimeNumbers = new HashSet<int> { 2, 3, 5, 7, 11, 13 };
                smallPrimeNumbers.Add (3);
                smallPrimeNumbers.Add (5);
                smallPrimeNumbers.Add (7);
                Console.WriteLine ("{0}", smallPrimeNumbers.Count);
                foreach(int val in smallPrimeNumbers)
                {
                    Console.WriteLine ("HashSet Value= {0}", val);
                }
            }
      }
}
Run Code Online (Sandbox Code Playgroud)

p.s*_*w.g 37

不,这不是一个错误.这正是HashSet应该如何运作的.

本HashSet<T>类提供高性能的设置操作.集合是一个不包含重复元素的集合,其元素没有特定的顺序.

因此,如果您要添加的项目已存在于集合中,则不会修改该集合.

如果你想要一个允许重复的集合,请查看List<T>.


Son*_*nül 10

从 HashSet<T> Class

HashSet类提供高性能的集合操作.集合是一个不包含重复元素的集合,其元素没有特定的顺序.

从 HashSet<T>.Add Method

返回值如果将元素添加到HashSet对象,则返回true;否则返回false. 如果元素已存在,则返回false.

HashSet是一种优化的集合.它的构造函数消除了非唯一元素.

例如;

string[] array = new string[] {"one", "one", "two", "two", "three", "three"};
HashSet<string> hash = new HashSet<string>(array);
string[] array2 = hash.ToArray();
Run Code Online (Sandbox Code Playgroud)

array2 将会 {"one", "two", "three"}

如果要添加重复值,则List<int>集合允许您添加重复值.