簡體   English   中英

如何檢查一個數組是否包含另一個數組的任何項目

[英]How to check if an array contains any item of another array

給定 2 個 int 數組,例如foobar ,檢查數組 bar 是否至少包含 foo 包含的一項的最有效方法是什么。 應該返回真/假。

我懷疑嵌套foreach但只是想知道是否有更好的方法?

使用 LINQ:

array1.Intersect(array2).Any()

注意:使用Any()確保在找到第一個相等對象時停止交集算法。

C#3:

bool result = bar.Any(el => foo.Contains(el));

C#4 並行執行:

bool result = bar.AsParallel().Any(el => foo.AsParallel().Contains(el));

是的嵌套循環,雖然一個是隱藏的:

bool AnyAny(int[] A, int[]B)
{
    foreach(int i in A)
       if (B.Any(b=> b == i))
           return true;
    return false;
}

另一種解決方案:

var result = array1.Any(l2 => array2.Contains(l2)) == true ? "its there": "not there";

如果您有類而不是像 int 等內置數據類型,則需要為您的類覆蓋 Override EqualsGetHashCode實現。

對於一次性隨機陣列方法,您的方法似乎是最快的。 如果對一個或兩個矩陣進行排序、它們的上限/下限已知,或者其中一個矩陣的更改方式比另一個少得多並且您執行許多檢查,則有一些方法可以提高效率。 問題是您可以准備各種散列、索引和提示,將搜索優化為幾乎沒有,但單獨的索引過程通常需要不止一次搜索。

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); } ----

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM