如何找到两个HashSet的补充

时间:2012-11-30 09:29:45

标签: c# linq

我有两个HashSet - setA和setB。

  1. 我们怎样才能找到setA和setB的补充?
  2. 交叉代码是找到交集的最佳方法吗?
  3. 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?

    参考

    1. What is the difference between HashSet<T> and List<T>?
    2. Intersection of multiple lists with IEnumerable.Intersect()
    3. Comparing two hashsets
    4. Compare two hashsets?
    5. Quickest way to find the complement of two collections in C#

2 个答案:

答案 0 :(得分:2)

  

1 - 我们如何找到setA和setB的补充?

使用HashSet<T>.Except Method

//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,用于创建新的HashSetIntersectWith,用于修改第一个:

// setA and setB unchanged
HashSet<string> intersection = setA.Intersect(setB);

// setA gets modified and holds the result
setA.IntersectWith(setB);