我想创建一个表示整数集的类,使用 HashSet<int>
.我希望它使用该内部容器跟踪集合中包含哪些值。到目前为止,我已经这样做了:
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
添加一些值,但我看不到这如何跟踪集合中包含哪些值。有什么想法吗?
最佳答案
哈希集有一个 Contains
允许您检查值是否在集合中的方法。
此外,HashSet<T>
实现 ISet<T>
接口(interface),因此提供了许多处理集合的方法,例如并集、交集以及确定一组值是集合的(适当的)超集还是子集。
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
顺便说一句,你知道collection initializer吗?语法?
您也可以foreach
在集合上获取它包含的每个元素(以未指定的顺序):
foreach(int value in intTest)
{
// Do something with value.
}
或者将其转换为数组或可变列表(也以未指定的顺序):
int[] arr = intTest.ToArray();
List<int> lst = intTest.ToList();
关于c# - 使用 HashSet<int> 创建整数集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14882287/