比较c#中数组的最简单方法。

时间:2021-08-04 14:04:47

In Java, Arrays.equals() allows to easily compare the content of two basic arrays (overloads are available for all the basic types).

在Java中,arrays .equals()允许轻松地比较两个基本数组的内容(所有基本类型都可以使用重载)。

Is there such a thing in C#? Is there any "magic" way of comparing the content of two arrays in C#?

在c#中有这样的东西吗?有什么“神奇”的方法来比较c#中两个数组的内容吗?

11 个解决方案

#1


172  

You could use SequenceEqual. This works for any IEnumerable<T>, not just arrays.

您可以使用SequenceEqual。这适用于任何IEnumerable ,不只是数组。

#2


44  

Use SequenceEqual in LINQ.

在LINQ中使用SequenceEqual。

int[] arr1 = new int[] { 1,2,3};
int[] arr2 = new int[] { 3,2,1 };

Console.WriteLine(arr1.SequenceEqual(arr2)); // false
Console.WriteLine(arr1.Reverse().SequenceEqual(arr2)); // true

#3


22  

Also for arrays (and tuples) you can use new interfaces from .NET 4.0: IStructuralComparable and IStructuralEquatable. Using them you can not only check equality of arrays but also compare them.

对于数组(和元组),还可以使用. net 4.0中的新接口:istructural和IStructuralEquatable。使用它们,不仅可以检查数组的相等性,还可以对它们进行比较。

static class StructuralExtensions
{
    public static bool StructuralEquals<T>(this T a, T b)
        where T : IStructuralEquatable
    {
        return a.Equals(b, StructuralComparisons.StructuralEqualityComparer);
    }

    public static int StructuralCompare<T>(this T a, T b)
        where T : IStructuralComparable
    {
        return a.CompareTo(b, StructuralComparisons.StructuralComparer);
    }
}

{
    var a = new[] { 1, 2, 3 };
    var b = new[] { 1, 2, 3 };
    Console.WriteLine(a.Equals(b)); // False
    Console.WriteLine(a.StructuralEquals(b)); // True
}
{
    var a = new[] { 1, 3, 3 };
    var b = new[] { 1, 2, 3 };
    Console.WriteLine(a.StructuralCompare(b)); // 1
}

#4


14  

For .NET 4.0 and higher you can compare elements in array or tuples via using StructuralComparisons type:

对于。net 4.0或更高版本,您可以使用结构比较类型来比较数组或元组中的元素:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };

Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)

IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

#5


10  

SequenceEqual will only return true if two conditions or met.

只有当两个条件或满足时,SequenceEqual才返回true。

  1. They contain the same elements.
  2. 它们包含相同的元素。
  3. The elements are in the same order.
  4. 元素的顺序是一样的。

If you only want to check if they contain the same elements regardless of their order and your problem is of the type

如果您只想检查它们是否包含相同的元素,而不管它们的顺序和您的问题是类型的

Does values2 contain all the values contained in values1?

values2是否包含values1中包含的所有值?

you can use LINQ extension method Enumerable.Except and then check if the result has any value. Here's an example

您可以使用LINQ extension方法Enumerable。除了,然后检查结果是否有任何值。这里有一个例子

int[] values1 = { 1, 2, 3, 4 };
int[] values2 = { 1, 2, 5 };
var result = values1.Except(values2);
if(result.Count()==0)
{
   //They are the same
}
else
{
    //They are different
}

And also by using this you get the different items as well automatically. Two birds with one stone.

通过使用它,你也可以自动地得到不同的项。一举两得。

Keep in mind, if you execute your code like this

请记住,如果您像这样执行代码

var result = values2.Except(values1);

you will get different results.

你会得到不同的结果。

In my case I have a local copy of an array and want to check if anything has been removed from the original array so I use this method.

在我的例子中,我有一个数组的本地副本,并且想要检查是否已经从原始数组中删除了任何东西,所以我使用了这个方法。

#6


5  

For unit tests, you can use CollectionAssert.AreEqual instead of Assert.AreEqual.

对于单元测试,可以使用CollectionAssert。AreEqual代替Assert.AreEqual。

It is probably the easiest way.

这可能是最简单的方法。

#7


1  

elementwise compare ? what about

elementwise比较?是什么

public void Linq78a()
{
 int[] numbers1 = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 bool bb = numbers.Zip(numbers1, (a, b) => (a == b)).Any(p => !p);
 if (!bb) Console.WriteLine("Lists are equal (bb)");
   else Console.WriteLine("Lists are not equal (bb)");
}

Replace the (a==b) condition by anything you'd like to compare in a and b.

将(a==b)条件替换为您想比较的a和b中的任何条件。

(this combines two examples from MSDN developer Linq samples)

(这结合了来自MSDN开发人员Linq示例的两个示例)

#8


1  

I did this in visual studios and it worked perfectly; comparing arrays index by index with short this code.

我在视觉工作室做过这个实验,效果很好;将数组索引按索引与短代码进行比较。

private void compareButton_Click(object sender, EventArgs e)
        {
            int[] answer = { 1, 3, 4, 6, 8, 9, 5, 4, 0, 6 };
            int[] exam = { 1, 2, 3, 6, 8, 9, 5, 4, 0, 7 };

            int correctAnswers = 0;
            int wrongAnswers = 0;

            for (int index = 0; index < answer.Length; index++)
            {
                if (answer[index] == exam[index])
                {
                    correctAnswers += 1;
                }
                else
                {
                    wrongAnswers += 1;
                }
            }

            outputLabel.Text = ("The matching numbers are " + correctAnswers +
                "\n" + "The non matching numbers are " + wrongAnswers);
        }

the output will be; The matching numbers are 7 The non matching numbers are 3

输出将;匹配数是7,非匹配数是3

#9


1  

For some applications may be better:

对于某些应用可能更好:

string.Join("", arr1) == string.Join("", arr2)

#10


0  

Here's a strange implementation.

这是一个奇怪的实现。

    static bool ArraysEqual<T>(T[] a, T[] b)
    {
        int k = 0;
        return a.All(x => x.Equals(b[k++]));
    }

#11


0  

If you would like to handle null inputs gracefully, and ignore the order of items, try the following solution:

如果您想优雅地处理空输入,并忽略项的顺序,请尝试以下解决方案:

static class Extensions
{
    public static bool ItemsEqual<TSource>(this TSource[] array1, TSource[] array2)
    {
        if (array1 == null && array2 == null)
            return true;
        if (array1 == null || array2 == null)
            return false;
        return array1.Count() == array2.Count() && !array1.Except(array2).Any();
    }
}

The test code looks like:

测试代码如下:

class Program
{
    static void Main(string[] args)
    {
        int[] a1 = new int[] { 1, 2, 3 };
        int[] a2 = new int[] { 3, 2, 1 };
        int[] a3 = new int[] { 1, 3 };
        int[] a4 = null;
        int[] a5 = null;
        int[] a6 = new int[0];

        Console.WriteLine(a1.ItemsEqual(a2)); // Output: True.
        Console.WriteLine(a2.ItemsEqual(a3)); // Output: False.
        Console.WriteLine(a4.ItemsEqual(a5)); // Output: True. No Exception.
        Console.WriteLine(a4.ItemsEqual(a3)); // Output: False. No Exception.
        Console.WriteLine(a5.ItemsEqual(a6)); // Output: False. No Exception.
    }
}

#1


172  

You could use SequenceEqual. This works for any IEnumerable<T>, not just arrays.

您可以使用SequenceEqual。这适用于任何IEnumerable ,不只是数组。

#2


44  

Use SequenceEqual in LINQ.

在LINQ中使用SequenceEqual。

int[] arr1 = new int[] { 1,2,3};
int[] arr2 = new int[] { 3,2,1 };

Console.WriteLine(arr1.SequenceEqual(arr2)); // false
Console.WriteLine(arr1.Reverse().SequenceEqual(arr2)); // true

#3


22  

Also for arrays (and tuples) you can use new interfaces from .NET 4.0: IStructuralComparable and IStructuralEquatable. Using them you can not only check equality of arrays but also compare them.

对于数组(和元组),还可以使用. net 4.0中的新接口:istructural和IStructuralEquatable。使用它们,不仅可以检查数组的相等性,还可以对它们进行比较。

static class StructuralExtensions
{
    public static bool StructuralEquals<T>(this T a, T b)
        where T : IStructuralEquatable
    {
        return a.Equals(b, StructuralComparisons.StructuralEqualityComparer);
    }

    public static int StructuralCompare<T>(this T a, T b)
        where T : IStructuralComparable
    {
        return a.CompareTo(b, StructuralComparisons.StructuralComparer);
    }
}

{
    var a = new[] { 1, 2, 3 };
    var b = new[] { 1, 2, 3 };
    Console.WriteLine(a.Equals(b)); // False
    Console.WriteLine(a.StructuralEquals(b)); // True
}
{
    var a = new[] { 1, 3, 3 };
    var b = new[] { 1, 2, 3 };
    Console.WriteLine(a.StructuralCompare(b)); // 1
}

#4


14  

For .NET 4.0 and higher you can compare elements in array or tuples via using StructuralComparisons type:

对于。net 4.0或更高版本,您可以使用结构比较类型来比较数组或元组中的元素:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };

Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)

IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

#5


10  

SequenceEqual will only return true if two conditions or met.

只有当两个条件或满足时,SequenceEqual才返回true。

  1. They contain the same elements.
  2. 它们包含相同的元素。
  3. The elements are in the same order.
  4. 元素的顺序是一样的。

If you only want to check if they contain the same elements regardless of their order and your problem is of the type

如果您只想检查它们是否包含相同的元素,而不管它们的顺序和您的问题是类型的

Does values2 contain all the values contained in values1?

values2是否包含values1中包含的所有值?

you can use LINQ extension method Enumerable.Except and then check if the result has any value. Here's an example

您可以使用LINQ extension方法Enumerable。除了,然后检查结果是否有任何值。这里有一个例子

int[] values1 = { 1, 2, 3, 4 };
int[] values2 = { 1, 2, 5 };
var result = values1.Except(values2);
if(result.Count()==0)
{
   //They are the same
}
else
{
    //They are different
}

And also by using this you get the different items as well automatically. Two birds with one stone.

通过使用它,你也可以自动地得到不同的项。一举两得。

Keep in mind, if you execute your code like this

请记住,如果您像这样执行代码

var result = values2.Except(values1);

you will get different results.

你会得到不同的结果。

In my case I have a local copy of an array and want to check if anything has been removed from the original array so I use this method.

在我的例子中,我有一个数组的本地副本,并且想要检查是否已经从原始数组中删除了任何东西,所以我使用了这个方法。

#6


5  

For unit tests, you can use CollectionAssert.AreEqual instead of Assert.AreEqual.

对于单元测试,可以使用CollectionAssert。AreEqual代替Assert.AreEqual。

It is probably the easiest way.

这可能是最简单的方法。

#7


1  

elementwise compare ? what about

elementwise比较?是什么

public void Linq78a()
{
 int[] numbers1 = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 bool bb = numbers.Zip(numbers1, (a, b) => (a == b)).Any(p => !p);
 if (!bb) Console.WriteLine("Lists are equal (bb)");
   else Console.WriteLine("Lists are not equal (bb)");
}

Replace the (a==b) condition by anything you'd like to compare in a and b.

将(a==b)条件替换为您想比较的a和b中的任何条件。

(this combines two examples from MSDN developer Linq samples)

(这结合了来自MSDN开发人员Linq示例的两个示例)

#8


1  

I did this in visual studios and it worked perfectly; comparing arrays index by index with short this code.

我在视觉工作室做过这个实验,效果很好;将数组索引按索引与短代码进行比较。

private void compareButton_Click(object sender, EventArgs e)
        {
            int[] answer = { 1, 3, 4, 6, 8, 9, 5, 4, 0, 6 };
            int[] exam = { 1, 2, 3, 6, 8, 9, 5, 4, 0, 7 };

            int correctAnswers = 0;
            int wrongAnswers = 0;

            for (int index = 0; index < answer.Length; index++)
            {
                if (answer[index] == exam[index])
                {
                    correctAnswers += 1;
                }
                else
                {
                    wrongAnswers += 1;
                }
            }

            outputLabel.Text = ("The matching numbers are " + correctAnswers +
                "\n" + "The non matching numbers are " + wrongAnswers);
        }

the output will be; The matching numbers are 7 The non matching numbers are 3

输出将;匹配数是7,非匹配数是3

#9


1  

For some applications may be better:

对于某些应用可能更好:

string.Join("", arr1) == string.Join("", arr2)

#10


0  

Here's a strange implementation.

这是一个奇怪的实现。

    static bool ArraysEqual<T>(T[] a, T[] b)
    {
        int k = 0;
        return a.All(x => x.Equals(b[k++]));
    }

#11


0  

If you would like to handle null inputs gracefully, and ignore the order of items, try the following solution:

如果您想优雅地处理空输入,并忽略项的顺序,请尝试以下解决方案:

static class Extensions
{
    public static bool ItemsEqual<TSource>(this TSource[] array1, TSource[] array2)
    {
        if (array1 == null && array2 == null)
            return true;
        if (array1 == null || array2 == null)
            return false;
        return array1.Count() == array2.Count() && !array1.Except(array2).Any();
    }
}

The test code looks like:

测试代码如下:

class Program
{
    static void Main(string[] args)
    {
        int[] a1 = new int[] { 1, 2, 3 };
        int[] a2 = new int[] { 3, 2, 1 };
        int[] a3 = new int[] { 1, 3 };
        int[] a4 = null;
        int[] a5 = null;
        int[] a6 = new int[0];

        Console.WriteLine(a1.ItemsEqual(a2)); // Output: True.
        Console.WriteLine(a2.ItemsEqual(a3)); // Output: False.
        Console.WriteLine(a4.ItemsEqual(a5)); // Output: True. No Exception.
        Console.WriteLine(a4.ItemsEqual(a3)); // Output: False. No Exception.
        Console.WriteLine(a5.ItemsEqual(a6)); // Output: False. No Exception.
    }
}