在C#中比较数组 [英] Comparing arrays in C#
本文介绍了在C#中比较数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个数组对方。我想这code,得到了以下错误。
静态布尔ArraysEqual(阵列A1,A2阵列)
{
IF(A1 == A2)
返回true; IF(A1 == NULL || A2 == NULL)
返回false; 如果(a1.Length!= a2.Length)
返回false; IList的list1的= A1,列表2 = A2; //错误CS0305:使用泛型类型'System.Collections.Generic.IList< T>'要求'1'类型参数
的for(int i = 0; I< a1.Length;我++)
{
如果(!的Object.Equals(list1的[I],列表2 [i]))//错误CS0021:不能适用与[]索引到类型的前pression'的IList(X2)
返回false;
}
返回true;
}
为什么我得到这个错误?我去了一个低技术的解决方案,这样做,它工作得很好,但我需要复制/粘贴几次每种类型。
静态布尔ArraysEqual(字节[] A1,字节[] A2)
{
IF(A1 == A2)
返回true; IF(A1 == NULL || A2 == NULL)
返回false; 如果(a1.Length!= a2.Length)
返回false; 的for(int i = 0; I< a1.Length;我++)
{
IF(A1 [I]!= A2 [I])
返回false;
}
返回true;
}
解决方案
为什么我得到这个错误? - 也许,你没有 System.Collections中使用;
的文件的顶部 - 只有使用System.Collections.Generic;
- 然而,仿制药可能更安全 - 见下:
静态布尔ArraysEqual< T>(T [] A1,T [] A2)
{
如果(的ReferenceEquals(A1,A2))
返回true; IF(A1 == NULL || A2 == NULL)
返回false; 如果(a1.Length!= a2.Length)
返回false; EqualityComparer< T>比较器= EqualityComparer< T> .DEFAULT;
的for(int i = 0; I< a1.Length;我++)
{
如果(!comparer.Equals(A1 [I],A2 [I]))返回false;
}
返回true;
}
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;
}
解决方案
"Why do i get that error?" - probably, you don't have "using System.Collections;
" at the top of the file - only "using System.Collections.Generic;
" - however, generics are probably safer - see below:
static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1,a2))
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i])) return false;
}
return true;
}
这篇关于在C#中比较数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文