c# - 使用 HashSet<int> 创建整数集

标签 c# int set

我想创建一个表示整数集的类,使用 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/

相关文章:

Java:如何从字符串和整数计算答案

Python - 从另一个列表中删除一组列表

c# - C# 如何决定将哪个枚举值作为返回值?有什么规定吗?

c# - 手动注册所有类(class)还是有自动方式?

android - 具有可绘制值的字符串数组到 int 数组

Java:是否有可能制作一组方法或任何类似的东西?

algorithm - 用给定的间隔覆盖所有数字

c# - 如何在数据表中获取不同的记录?

c# - 报表查看器文本框可见性表达式

java - 为什么 08 在 Java 中不是有效的整数文字?