C# 如何检查一个数组是否包含另一个数组的任何项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2266012/
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
How to check if an array contains any item of another array
提问by raklos
Given 2 int arrays e.g, foo
and bar
, what's the most efficient way to check that the array bar contains at least one item that foo contains. should return true/false.
给定 2 个 int 数组,例如,foo
和bar
,检查数组 bar 是否至少包含 foo 包含的一项的最有效方法是什么。应该返回真/假。
I'm suspecting nested foreach
but just wondering if there's a nicer way?
我怀疑嵌套foreach
但只是想知道是否有更好的方法?
采纳答案by Olli
Using LINQ:
使用 LINQ:
array1.Intersect(array2).Any()
Note: Using Any()
assures that the intersection algorithm stops when the first equal object is found.
注意:使用可Any()
确保在找到第一个相等对象时停止交集算法。
回答by James Curran
Yes nested loops, although one is hidden:
是的嵌套循环,虽然一个是隐藏的:
bool AnyAny(int[] A, int[]B)
{
foreach(int i in A)
if (B.Any(b=> b == i))
return true;
return false;
}
回答by Alex Bagnolini
C#3:
C#3:
bool result = bar.Any(el => foo.Contains(el));
C#4 parallel execution:
C#4 并行执行:
bool result = bar.AsParallel().Any(el => foo.AsParallel().Contains(el));
回答by SF.
For one-shot random-array approach, your method seems to be the fastest. There are methods that would make it way more efficient if one or both matrices are sorted, their upper/lower bounds are known, or one of them changes way more rarely than the other one and you perform many checks. Thing is you can prepare various hashes, indices and hints that will optimize the search to nearly nothing, but the process of indexing alone will usually take more than a single search.
对于一次性随机阵列方法,您的方法似乎是最快的。如果对一个或两个矩阵进行排序、它们的上限/下限已知,或者其中一个矩阵的更改方式比另一个少得多并且您执行许多检查,则有一些方法可以提高效率。问题是您可以准备各种散列、索引和提示,将搜索优化为几乎没有,但单独的索引过程通常需要不止一次搜索。
回答by Gauravsa
Another solution:
另一种解决方案:
var result = array1.Any(l2 => array2.Contains(l2)) == true ? "its there": "not there";
If you have class instead of built in datatypes like int etc, then need to override Override Equals
and GetHashCode
implementation for your class.
如果你有类而不是像 int 等内置数据类型,那么需要覆盖你的类的OverrideEquals
和GetHashCode
implementation。
回答by ilir jusufi
static void Main(string[] args)
int[] arr1 = { 16, 48, 40, 32, 5, 7 };
int[] arr2 = { 48, 32, 16, 40, 56, 72, 16, 16, 16, 16, 16, 5, 7, 6, 56 };
int k = 0;
for (int i = 0; i < arr1.Length; i++)
{
for (int j = 0; j < arr2.Length; j++)
{
if (arr1[i] == arr2[j])
{
k++;
break;
}
}
}
if (arr1.Length == k)
{
Console.WriteLine(true);
}
else
Console.WriteLine(false);
}
----