I want to create an class that represents an integer set using a HashSet<int>
. I want it to keep track of which values are included in the set using that internal container. I've done this so far:
class SetInteger
{
HashSet<int> intTest= new HashSet<int>();
intTest.Add(1);
intTest.Add(2);
intTest.Add(3);
intTest.Add(4);
intTest.Add(5);
intTest.Add(6);
intTest.Add(7);
intTest.Add(8);
intTest.Add(9);
intTest.Add(10);
}
So, here I think I'm adding some values to the HashSet
, but I dont see how this can keep track of which values that are included in the set. Any ideas?
The hash set has a Contains
method that allows you to check whether a value is in the set.
In addition, the HashSet<T>
implements the ISet<T>
interface and therefore provides many methods for working with sets, such as union, intersection and determining if a set of values is a (proper) super- or subset of your set.
HashSet<int> intTest = new HashSet<int>()
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
bool has4 = intTest.Contains(4); // Returns true
bool has11 = intTest.Contains(11); // Returns false
bool result = intTest.IsSupersetOf(new []{ 4, 6, 7 }); // Returns true
By the way, did you know about the collection initializer syntax?
You can also foreach
on the set to get each element it contains (in an unspecified order):
foreach(int value in intTest)
{
// Do something with value.
}
Or convert it to an array or mutable list (also in an unspecified order):
int[] arr = intTest.ToArray();
List<int> lst = intTest.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With