问题
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