【问题标题】:Determine the relative complement of two IEnumerable<T> sets in .NET确定 .NET 中两个 IEnumerable<T> 集的相对补集
【发布时间】:2010-06-02 18:59:59
【问题描述】:

有没有简单的方法来获得两组的relative complement?也许使用 LINQ?

我必须找到集合 A 相对于 B 的相对互补。A 和 B 都是 HashSet&lt;T&gt; 类型,但我认为算法可以更通用(IEnumerable&lt;T&gt; 甚至 ISet&lt;T&gt;)?

我可以在 VB.NET 或 C# 中使用解决方案。

【问题讨论】:

    标签: c# .net vb.net linq set


    【解决方案1】:

    你试过Enumerable.Except吗?

    setB.Except(setA)
    

    例子:

    HashSet<int> setB = new HashSet<int> { 1, 2, 3, 4, 5 };
    HashSet<int> setA = new HashSet<int> { 1, 3, 5, 7 };
    HashSet<int> result = new HashSet<int>(setB.Except(setA));
    
    foreach (int x in result)
        Console.WriteLine(x);
    

    结果:

    2 4

    【讨论】:

      猜你喜欢
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多