Attemping to add a value to a HashSet doesn't change the amount of values in it

南笙酒味 提交于 2020-06-10 19:37:02

问题


I have a HashSet and when I use the Add method of the collection, nothing is added. The output is still 2, 3, 5, 7, 11, 13 and the output from .Count is 6.

Is this a bug or am I doing something wrong here?

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);
                }
            }
      }
}

回答1:


No, this is not a bug. This is precisely how a HashSet is supposed to work.

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.

So, if the item you are trying to add already exists in the set, the set is not modified.

If you want a collection which does allow duplicates, look at List<T>.




回答2:


From HashSet<T> Class

The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

From HashSet<T>.Add Method

Return Value true if the element is added to the HashSet object; false if the element is already present.

HashSet is a kind of optimized collection. Its constructor eliminates the non-unique elements.

For example;

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

array2 will be {"one", "two", "three"}

If you want to add duplicate values, List<int> collection allows you to add duplicate values.




回答3:


One of the main features of HashSet is ensuring there are no duplicates



来源:https://stackoverflow.com/questions/20819248/attemping-to-add-a-value-to-a-hashset-doesnt-change-the-amount-of-values-in-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!