比较两个 .NET Array 对象 [英] Compare two .NET Array objects

查看:32
本文介绍了比较两个 .NET Array 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较两个 .NET 数组.这是比较字节数组的明显实现:

I am trying to compare two .NET arrays. Here is an obvious implementation for comparing arrays of bytes:

bool AreEqual(byte[] a, byte[] b){
    if(a.Length != b.Length)
        return false;
    for(int i = 0; i < a.Length; i++)
        if(a[i] != b[i])
            return false;

    return true;
}

可以在此处查看更精细的方法(通过 Google).

A more refined approach can be seen here (via Google).

  1. 最简单的方法是什么(使用less代码但可读)来比较两个.NET 数组?
  2. 最有效的方法是什么比较两个 .NET 数组?

推荐答案

Kathy 的方法对我来说似乎很好.我个人允许明确指定比较器:

Kathy's approach seems a good one to me. I'd personally allow the comparer to be specified explicitly:

bool AreEqual<T>(T[] a, T[] b)
{
    return AreEqual(a, b, EqualityComparer<T>.Default);
}

bool AreEqual<T>(T[] a, T[] b, IEqualityComparer<T> comparer)
{
    // Handle identity comparison, including comparing nulls
    if (a == b)
    {
        return true;
    }

    if (a == null || b == null)
    {
        return false;
    }

    if(a.Length != b.Length)
    {
        return false;
    }

    for(int i = 0; i < a.Length; i++)
    {
        if(!comparer.Equals(a[i], b[i]))
        {
            return false;
        }
    }
    return true;
}

CMS 提到的 SequenceEqual 很好,但由于它对 IEnumerable 的普遍性,我认为如果长度不相等,它就不能提前".(不过,它可能会检查实现 IList 的两个序列,以直接检查 Count.)您可以概括一下,使用 IList

SequenceEqual as mentioned by CMS is good, but due to its generality over IEnumerable<T> I don't think it can do the "early out" if the length aren't equal. (It's possible that it checks for both sequences implementing IList though, to check Count directly.) You could generalise a little more, to use IList<T>

bool AreEqual<T>(IList<T> a, IList<T> b, IEqualityComparer<T> comparer)
{
    if(a.Count != b.Count)
    {
        return false;
    }
    for(int i = 0; i < a.Count; i++)
    {
        if(!comparer.Equals(a[i], b[i]))
        {
            return false;
        }
    }
    return true;
}

直接数组版本可能是最有效的 - 添加通用性和抽象性通常会影响性能,尽管它是否重要取决于您的应用.

The straight array version will probably be the most efficient - adding generality and abstraction usually hits performance, although whether it's significant will depend on your app.

这篇关于比较两个 .NET Array 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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