staticvoidMain(string[] args) { HashSet<string> hashSet = new HashSet<string>(); hashSet.Add("A"); hashSet.Add("B"); hashSet.Add("C"); hashSet.Add("D"); hashSet.Add("D"); Console.WriteLine("The number of elements is: {0}", hashSet.Count); Console.ReadKey(); }
输出结果就是ABCD,最后一个重复的D被忽略了。
HashSet的一些常用方法
Contains方法
确认HashSet是否含有某元素
1
hashset.contains("D");
Remove方法
在HashSet中移除某元素
1
hashset.Remove(item);
Clear方法
删除HashSet里面的所有元素
isProperSubsetOf方法
判断HashSet是否为某一集合的完全子集
1 2 3 4 5 6 7
HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D" }; HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X" }; HashSet<string> setC = new HashSet<string>() { "A", "B", "C", "D", "E" }; if (setA.IsProperSubsetOf(setC)) //是子集输出1,不是输出0 Console.WriteLine("setC contains all elements of setA."); if (!setA.IsProperSubsetOf(setB)) Console.WriteLine("setB does not contains all elements of setA.");