我有两个HashSet - setA和setB。
CODE
string stringA = "A,B,A,A";
string stringB = "C,A,B,D";
HashSet<string> setA = new HashSet<string>(stringA.Split(',').Select(t => t.Trim()));
HashSet<string> setB = new HashSet<string>(stringB.Split(',').Select(t => t.Trim()));
//Intersection - Present in A and B
HashSet<string> intersectedSet = new HashSet<string>( setA.Intersect(setB));
//Complemenet - Present in A; but not present in B
更新:
使用OrdianlIgnoreCase
忽略案例敏感性How to use HashSet<string>.Contains() method in case -insensitive mode?
参考:
答案 0 :(得分:2)
1 - 我们如何找到setA和setB的补充?
//Complemenet - Present in A; but not present in B
HashSet<string> ComplemenetSet = new HashSet<string>(setA.Except(setB));
尝试使用以下字符串。
string stringA = "A,B,A,E";
string stringB = "C,A,B,D";
ComplementSet将包含E
2 - 交叉点的代码是找到交叉点的最佳方法吗?
可能,是
答案 1 :(得分:2)
您可以使用Except
获取A或B的补码。要获得对称补码,请使用SymmetricExceptWith
。
setA.SymmetricExceptWith(setB);
请注意,此修改了 setA
。要获得交集,有两种方法:Intersect
,用于创建新的HashSet
,IntersectWith
,用于修改第一个:
// setA and setB unchanged
HashSet<string> intersection = setA.Intersect(setB);
// setA gets modified and holds the result
setA.IntersectWith(setB);