检查HashSet是否包含C#中的指定元素
要检查HashSet是否包含指定的元素,代码如下-
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
HashSet<int> set1 = new HashSet<int>();
set1.Add(25);
set1.Add(50);
set1.Add(75);
set1.Add(100);
set1.Add(125);
set1.Add(150);
Console.WriteLine("Elements in HashSet1");
foreach(int val in set1){
Console.WriteLine(val);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(30);
set2.Add(60);
set2.Add(100);
set2.Add(150);
set2.Add(200);
set2.Add(250);
Console.WriteLine("Elements in HashSet2");
foreach(int val in set2){
Console.WriteLine(val);
}
Console.WriteLine("Do they share common elements? "+set1.Overlaps(set2));
Console.WriteLine("Does HashSet1 has element 60? "+set1.Contains(60));
Console.WriteLine("Does HashSet2 has element 60? "+set2.Contains(60));
}
}输出结果
这将产生以下输出-
Elements in HashSet1 25 50 75 100 125 150 Elements in HashSet2 30 60 100 150 200 250 Do they share common elements? True Does HashSet1 has element 60? False Does HashSet2 has element 60? True
示例
Let us now see another example;
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("Tim");
hashSet.Add("Jack");
hashSet.Add("Matt");
hashSet.Add("Steve");
hashSet.Add("David");
hashSet.Add("Kane");
hashSet.Add("Gary");
Console.WriteLine("Elements in HashSet");
foreach(string val in hashSet){
Console.WriteLine(val);
}
if (hashSet.Contains("Matt"))
Console.WriteLine("The element Matt is in the HashSet");
else
Console.WriteLine("The element Matt is not in the HashSet");
}
}输出结果
这将产生以下输出-
Elements in HashSet Tim Jack Matt Steve David Kane Gary The element Matt is in the HashSet
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短