在C#中,要判斷HashSet中是否存在某個元素,可以使用Contains()
方法。這是一個簡單的示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> myHashSet = new HashSet<int> { 1, 2, 3, 4, 5 };
int numberToCheck = 3;
if (myHashSet.Contains(numberToCheck))
{
Console.WriteLine($"{numberToCheck} 存在于 HashSet 中。");
}
else
{
Console.WriteLine($"{numberToCheck} 不存在于 HashSet 中。");
}
}
}
在這個示例中,我們創建了一個包含整數的HashSet,然后使用Contains()
方法檢查numberToCheck
是否存在于集合中。如果存在,我們輸出相應的消息,否則輸出另一條消息。