class A
{
//HashSet的集中用法
static void Main()
{
}
//1.
//这个 IsProperSubsetOf 用于判断 HashSet 是否为某一个集合的完全子集,可以看下面的例子:
public static void B()
{
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))
Console.WriteLine("setC contains all elements of setA.");
if (!setA.IsProperSubsetOf(setB))
Console.WriteLine("setB does not contains all elements of setA.");
}
//2.
//UnionWith方法常用于集合的合并,比如说下面的代码:
//当你执行完上面的代码,SetB 集合会被 SetA 集合吞掉,最后 SetA 集合将会是包括:"A", "B", "C", "D", "E", "X", and "Y" 。
public static void C()
{
HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X", "Y" };
setA.UnionWith(setB);
foreach (string str in setA)
{
Console.WriteLine(str);
}
}
//3.IntersectWith 方法常用于表示两个 HashSet 的交集,下面的例子或许会让你更加理解:
//输出A和C
public static void D()
{
HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };
setA.IntersectWith(setB);
foreach (string str in setA)
{
Console.WriteLine(str);
}
}
//4.SymmetricExceptWith 方法常用于修改一个 HashSet 来存放两个 HashSet 都是唯一的元素,
//换句话说,我要的就是两个集合都不全有的元素,如果还不明白的话,考虑下面的代码段:
//输出为:X,B,Y,D,E
public static void E()
{
HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };
setA.SymmetricExceptWith(setB);
foreach (string str in setA)
{
Console.WriteLine(str);
}
}
//5.ExceptWith 方法表示数学上的减法操作,
//这个时间复杂度是 O(N),假定你有两个HashSet 集合,分别叫 setA 和 setB,并且用了下面的语句。
//输出为:B,D,E
public static void F()
{
HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };
setA.ExceptWith(setB);
foreach (string str in setA)
{
Console.WriteLine(str);
}
}
}
Reference:https://zhuanlan.zhihu.com/p/338494553