比较 C# 中的数组 [英] Comparing arrays in C#

查看:40
本文介绍了比较 C# 中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将两个数组相互比较.我尝试了这段代码并得到了以下错误.

I am trying to compare two arrays with each other. I tried this code and got the following errors.

static bool ArraysEqual(Array a1, Array a2)
{
    if (a1 == a2)
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    IList list1 = a1, list2 = a2; //error CS0305: Using the generic type 'System.Collections.Generic.IList<T>' requires '1' type arguments
    for (int i = 0; i < a1.Length; i++)
    {
        if (!Object.Equals(list1[i], list2[i])) //error CS0021: Cannot apply indexing with [] to an expression of type 'IList'(x2)
            return false;
    }
    return true;
}

为什么我会收到那个错误?我选择了一个技术含量低的解决方案,这样做效果很好,但我需要为每种类型复制/粘贴几次.

Why do I get that error? I went for a low-tech solution and did this which works fine, but I need to copy/paste it several times for each type.

static bool ArraysEqual(byte[] a1, byte[] a2)
{
    if (a1 == a2)
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    for (int i = 0; i < a1.Length; i++)
    {
        if (a1[i] != a2[i])
            return false;
    }
    return true;
}

推荐答案

前提是你有 LINQ 可用并且不太在意性能,最简单的事情如下:

Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:

var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);

事实上,可能值得用 ReflectorILSpy 检查 SequenceEqual 方法实际上做了什么,因为它很可能针对特殊情况进行优化无论如何,数组值的情况!

In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual methods actually does, since it may well optimise for the special case of array values anyway!

这篇关于比较 C# 中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆