在 C# 中测试数组的相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/649444/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:45:21  来源:igfitidea点击:

Testing equality of arrays in C#

c#arrays

提问by SudheerKovalam

I have two arrays. For example:

我有两个数组。例如:

int[] Array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] Array2 = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8};

What is the best way to determine if they have the same elements?

确定它们是否具有相同元素的最佳方法是什么?

采纳答案by Sedat Kapanoglu

By using LINQyou can implement it expressively and performant:

通过使用LINQ,您可以富有表现力和高性能地实现它:

var q = from a in ar1
        join b in ar2 on a equals b
        select a;

bool equals = ar1.Length == ar2.Length && q.Count() == ar1.Length;

回答by Cerebrus

I have found the solution detailed hereto be a very clean way, though a bit verbose for some people.

我发现这里详述的解决方案是一种非常干净的方式,尽管对某些人来说有点冗长。

The best thing is that it works for other IEnumerables as well.

最好的事情是它也适用于其他 IEnumerables。

回答by Marc Gravell

Will the values always be unique? If so, how about (after checking equal length):

值总是唯一的吗?如果是这样,怎么样(检查等长后):

var set = new HashSet<int>(array1);
bool allThere = array2.All(set.Contains);

回答by eglasius

var shared = arr1.Intersect(arr2);
bool equals = arr1.Length == arr2.Length && shared.Count() == arr1.Length;

回答by Mike Nislick

You could also use SequenceEqual, provided the IEnumerable objects are sorted first.

您也可以使用SequenceEqual,前提是首先对 IEnumerable 对象进行排序。

int[] a1 = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };    
int[] a2 = new[] { 9, 1, 4, 5, 2, 3, 6, 7, 8 };    

bool equals = a1.OrderBy(a => a).SequenceEqual(a2.OrderBy(a => a));

回答by Allen

Use extension methods (which are new in 3.0). If the length of the Intersection of the two arrays equals that of their Union then the arrays are equal.

使用扩展方法(这是 3.0 中的新方法)。如果两个数组的交集长度等于它们并集的长度,则数组相等。

bool equals = arrayA.Intersect(arrayB).Count() == arrayA.Union(arrayB).Count()

Succinct.

简洁。

回答by Ohad Schneider

For the most efficient approach (Reflectoredfrom Microsoft code), see Stack Overflow question Comparing two collections for equality irrespective of the order of items in them.

有关最有效的方法(来自 Microsoft 代码的反射),请参阅 Stack Overflow 问题比较两个集合的相等性,而不管其中项目的顺序

回答by lukaszk

Framework 4.0 introduced IStructuralEquatable interface which helps to compare types such as arrays or tuples:

Framework 4.0 引入了 IStructuralEquatable 接口,它有助于比较数组或元组等类型:

 class Program
    {
        static void Main()
        {
            int[] array1 = { 1, 2, 3 };
            int[] array2 = { 1, 2, 3 };
            IStructuralEquatable structuralEquator = array1;
            Console.WriteLine(array1.Equals(array2));                                  // False
            Console.WriteLine(structuralEquator.Equals(array2, EqualityComparer<int>.Default));  // True

            // string arrays
            string[] a1 = "a b c d e f g".Split();
            string[] a2 = "A B C D E F G".Split();
            IStructuralEquatable structuralEquator1 = a1;
            bool areEqual = structuralEquator1.Equals(a2, StringComparer.InvariantCultureIgnoreCase);

            Console.WriteLine("Arrays of strings are equal:"+  areEqual);

            //tuples
            var firstTuple = Tuple.Create(1, "aaaaa");
            var secondTuple = Tuple.Create(1, "AAAAA");
            IStructuralEquatable structuralEquator2 = firstTuple;
            bool areTuplesEqual = structuralEquator2.Equals(secondTuple, StringComparer.InvariantCultureIgnoreCase);

            Console.WriteLine("Are tuples equal:" + areTuplesEqual);
            IStructuralComparable sc1 = firstTuple;
            int comparisonResult = sc1.CompareTo(secondTuple, StringComparer.InvariantCultureIgnoreCase);
            Console.WriteLine("Tuples comarison result:" + comparisonResult);//0
        }
    } 

回答by daebr

This will check that each array contains the same values in order.

这将检查每个数组是否按顺序包含相同的值。

int[] ar1 = { 1, 1, 5, 2, 4, 6, 4 };
int[] ar2 = { 1, 1, 5, 2, 4, 6, 4 };

var query = ar1.Where((b, i) => b == ar2[i]);

Assert.AreEqual(ar1.Length, query.Count());

回答by sumit10709893

    public static bool ValueEquals(Array array1, Array array2)
    {
        if( array1 == null && array2 == null )
        {
            return true;
        }

        if( (array1 == null) || (array2 == null) )
        {
            return false;
        }

        if( array1.Length != array2.Length )
        {
            return false;
        }
        if( array1.Equals(array2))
        {
           return true;
        }
        else
        {
            for (int Index = 0; Index < array1.Length; Index++)
            {
                if( !Equals(array1.GetValue(Index), array2.GetValue(Index)) )
                {
                    return false;
                }
            }
        }
        return true;
    }