使用HashSet <int>创建一个整数集</int>

时间:2013-02-14 19:13:08

标签: 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添加一些值,但是我没有看到它如何跟踪集合中包含的值。有什么想法吗?

5 个答案:

答案 0 :(得分:19)

哈希集有一个Contains方法,可以让你检查一个值是否在集合中。

此外,HashSet<T>实现了ISet<T>接口,因此提供了许多处理集合的方法,例如union,intersection和确定一组值是否(正确)超级或者你的集合的子集。

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();

答案 1 :(得分:0)

如果值已经存在,您可以使用HashSet Contains方法告诉!

示例:

if (intTest.Contains(5))
{
    // already has the value
}

答案 2 :(得分:0)

嗯......好吧,HashSet<T>实现了IEnumerable<T>,所以你总是可以做到这一点来弄清楚“那里已有什么”:

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);
var inThereNow = intTest.ToArray();  // [1,2,3,4,5,6,7,8,9,10]

还有bool Contains(T value)会告诉您集合中是否有特定值,IEnumerable<T> Union(IEnumerable<T> other)会告诉您两个集合的“或”,IEnumerable<T> Intersect(IEnumerable<T> other)会告诉您两组重叠......几乎任何IEnumerable<T>ISet<T>

中的任何内容

答案 3 :(得分:-1)

使用包含方法:http://msdn.microsoft.com/en-us/library/bb356440.aspx

希望这有帮助。

答案 4 :(得分:-2)

你可以试试这个。你只需要一个文本框和两个按钮。

HashSet<int> hs = new HashSet<int>();
    private void savedataonhashSet_Click(object sender, EventArgs e)
    {

        hs.Add(Convert.ToInt16(textBox1.Text));
   }

    private void checkduplicatevalue_Click(object sender, EventArgs e)
    {
        if (hs.Contains(00))          

        {
            MessageBox.Show("it is");
        }
        else
        {
            MessageBox.Show("not there");
        }
    }

如果你再次遇到问题,只需丢弃你的代码......