【问题标题】:How to find Complement of two HashSets如何找到两个哈希集的补码
【发布时间】:2012-11-18 12:03:29
【问题描述】:

我有两个 HashSet——setA 和 setB。

  1. 如何找到 setA 和 setB 的补集?
  2. 交叉路口的代码是找到交叉路口的最佳方法吗?

代码

 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#

【问题讨论】:

  • “我们如何找到setA和setB的补集?”不就是setA.Except(setB)吗?

标签: c# linq


【解决方案1】:

您可以使用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);

【讨论】:

    【解决方案2】:

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

    使用HashSet&lt;T&gt;.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 - 交叉点的代码是找到交叉点的最佳方法吗?

    应该是的

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多