C# 使用 Linq 确定一个序列是否包含另一个序列的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/407729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine if a sequence contains all elements of another sequence using Linq
提问by Bryan Watts
Given two sets of values:
给定两组值:
var subset = new[] { 2, 4, 6, 8 };
var superset = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
how do I determine if superset
contains all elements of subset
?
如何确定是否superset
包含 的所有元素subset
?
I have come up with this:
我想出了这个:
superset.Intersect(subset).Count() == subset.Count()
Is this the most logical and efficient method?
这是最合乎逻辑和最有效的方法吗?
采纳答案by Amy B
Count? How about Not Any?
数数?没有呢?
bool contained = !subset.Except(superset).Any();
回答by leppie
You could use Except and the resulting count should be 0.
您可以使用“除外”,结果计数应为 0。
Read up on MSDN for details of the parameters.
在 MSDN 上阅读有关参数的详细信息。
Example:
例子:
subset.Except(superset).Count() == 0
回答by Amy B
So, my other answer was pretty easy to use. But it's an O(n*m) solution.
所以,我的另一个答案很容易使用。但这是一个 O(n*m) 解决方案。
Here's a slightly less friendly O(n+m) solution. This should be used if superset is HUGE. It avoids repeatedly enumerating superset.
这是一个不太友好的 O(n+m) 解决方案。如果超集是巨大的,则应该使用它。它避免了重复枚举超集。
HashSet<int> hashSet = new HashSet<int>(superset);
bool contained = subset.All(i => hashSet.Contains(i));
回答by Anders
I have an extension method that uses the existing Contains()-method. I find it more intuitive than using Instersect() or Except().
我有一个使用现有 Contains() 方法的扩展方法。我发现它比使用 Instersect() 或 Except() 更直观。
public static bool ContainsAll<T>(this IEnumerable<T> source, IEnumerable<T> values)
{
return values.All(value => source.Contains(value));
}