簡體   English   中英

如何比較c#中的兩個數組並找到數組的完全匹配

[英]How to compare two arrays in c# and find the exact match of arrays

我想在c#中比較兩個數組。 如果匹配則轉到if條件否則轉到else條件。 我們怎樣才能在c#中做到這一點。

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
int[] numbers2 = new int[] { 1, 2, 3, 4, 5 };

我想比較兩個數組

if(numbers == numbers2){
   do something
}else{
   do something
}

您可以使用Enumerable.SequenceEqual()擴展方法。 它完全符合您的要求:

if (numbers.SequenceEqual(numbers2)) {
    // do something
} else {
    // do something else
}

您可以為數組創建擴展函數,它接受輸入另一個數組對象,然后使用HashSet可以比較兩個數組。 喜歡 -

if (numbers.ArrayEqual(number2){
// do this
}
else{
// do that
}

function static bool ArrayEqual(this int[] a, int []b)
{ 

  return a.Length == b.Length 
                         && new HashSet<string>(a).SetEquals(b);
}

暫無
暫無

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

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