简体   繁体   中英

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

I want to compare two array in c#. If they are matched go to if condition else go to the else condition. How can we do that in c#.

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

I want to compare the two arrays like

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

You can use the Enumerable.SequenceEqual() extension method. It does exactly what you want:

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

You can create a extension function for array, which takes input another array object and then using HashSet you can compare two arrays. Like -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM