问题描述
我想创建一个表示使用的HashSet℃的整数集的类; INT>
。我希望它跟踪哪些值包括在使用容器内部设置的。我到目前为止已经做到了这一点:
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);
}
所以,在这里我想我加入了一些值到 HashSet的
,但我没有看到这如何能保持跟踪包含在一套价值观。任何想法?
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?
推荐答案
HashSet的拥有的方法,可以让你检查一个值是否在设定的。
HashSet has a Contains
method that allows you to check whether a value is in the set.
此外, HashSet的
实现接口,因此提供了与集,如集,交集工作,确定一组值是一个超或子许多方法。您的设置
In addition the HashSet
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 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
顺便说一句,你了解的语法?
您也可以在的foreach
的设置得到它包含的每个元素(在未指定的顺序)
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();
这篇关于使用HashSet< int>创建一个整数集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!