gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:25:46 25 4
gpt4 key购买 nike

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

(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com