c# - 如何检查一个列表是否包含另一个列表的所有元素

标签 c# ienumerable contains

我想检查一个列表是否包含另一个列表的所有元素,例如:

(a,b,c,d) contains (c, a, d) = true
(a, b, c, d) contains (b, b, c, d) = false

我试过这样的事情:

static bool ContainsOther<T>(IEnumerable<T> a, IEnumerable<T> b)
{
    return new HashSet<T>(a).IsSupersetOf(new HashSet<T>(b));
}

但是它不能正确解决这个问题:
(a, b, c, d) 包含 (b, b, c, d) = false,它会说 true,但我想接收 假的

嵌套循环也是如此。

最佳答案

HashSet 是一个包含唯一元素的集合:

The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

所以这种行为是意料之中的。一种快速但肮脏的方法是使用字典对元素进行分组和计数:

static bool ContainsOther<T>(IEnumerable<T> a, IEnumerable<T> b)
{
    var left = a.GroupBy(i => i)
        .ToDictionary(g => g.Key, g => g.Count());
    // or just cycle through elements of `b` and reduce count in a
    var right = b.GroupBy(i => i)
        .ToDictionary(g => g.Key, g => g.Count()); 

    foreach (var (key, value) in right)
    {
        if (!left.TryGetValue(key, out var leftValue) || leftValue < value)
            return false;
    }

    return true;
}

关于c# - 如何检查一个列表是否包含另一个列表的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74326851/

相关文章:

java - 如何比较 Map 和 List

c# - Selenium Webdriver 不尊重 cookie 或缓存图像

c# - 获取实现特定开放通用类型的所有类型

c# - 是否有等同于 unix 命令 uniq 的 Linq

c# - collections.Contains(T) 方法

vb.net - 要检查数组是否仅包含来自另一个数组的元素,VB.NET

c# - 在 C# 中地理定位 IP 地址

c# - 如何创建一个dll以在单独的项目中引用和使用?

c# - Roslyn - 从 yield'ed IEnumerable<T> 创建一个 SeparatedList<T>

c# - 将字典转换为两个列表的最佳方法