比较两个.NET Array对象 [英] Compare two .NET Array objects
问题描述
我想比较两个.NET数组。这是一个明显的实现比较字节数组:
布尔AreEqual(byte []的一个,byte []的B){
如果(则为a.length!= b.length个)
返回false;
的for(int i = 0; I<则为a.length;我++)
如果(A [1]!= B [I])
返回false;
返回true;
}
一个更精确的方法可以看出这里一>(通过谷歌)。
- 什么是最简单的方法(使用更少 code,但可读)来比较两个 .NET数组?
- 什么是最有效的方法 比较两个.NET数组?
凯西的做法似乎是一个不错的给我。我个人允许明确指定的比较器:
布尔AreEqual< T>(T [] A,T []二)
{
返回AreEqual(A,B,EqualityComparer< T> .DEFAULT);
}
布尔AreEqual< T>(T [] A,T [] B,的IEqualityComparer< T>比较器)
{
若(a == NULL和放大器;和b == NULL)
{
返回true;
}
若(a == NULL || b == NULL)
{
返回false;
}
如果(则为a.length!= b.length个)
{
返回false;
}
的for(int i = 0; I<则为a.length;我++)
{
如果(!comparer.Equals(A [1],B [i]于))
{
返回false;
}
}
返回true;
}
SequenceEqual所提到的CMS是不错的,但由于其通用性超过的IEnumerable< T>
我不认为如果长度能做到早出不相等。 (这是可能的,它会检查两个序列实施的IList不过,检查直接计数。)你可以概括一点,使用的IList< T>
布尔AreEqual< T>(IList的< T>一种,IList的< T> B,的IEqualityComparer< T>比较器)
{
如果(a.Count!= b.Count)
{
返回false;
}
的for(int i = 0; I< a.Count;我++)
{
如果(!comparer.Equals(A [1],B [i]于))
{
返回false;
}
}
返回true;
}
直阵列版本将可能是最有效的 - 增加一般性和抽象通常命中的表现,但无论是的显著的将取决于您的应用程序
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;
}
A more refined approach can be seen here (via Google).
- What is the simplest way (using less code but readable) to compare two .NET arrays?
- What is the most efficient way compare two .NET arrays?
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)
{
if (a == null && b == null)
{
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;
}
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屋!