环境:数组A 和数组B
int[] ArrayA = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] ArrayB = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8};
我们需要比较的是数组的内容,而不是数组的对象引用所以我们不能想当然的用Array.Equals(ArrayA,ArrayB)(结果为false)
现在我们来看看怎样比较数组的内容,当然你可以用循环来比较,在此我们就不谈循环比较的方法了。现在我们看看其他的方法:
方法一:利用泛型方法
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; } [html] view plaincopyprint?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; } 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;
}
方法二:Enumerable.SequenceEqual的扩展方法:确定两个序列是否相等的相等比较。(要求3.0以上)具体可以查看msdn:aspx">http://msdn.microsoft.com/en-us/library/bb348567.aspx,当然他的适用范围更广。
bool equals = ArrayA.OrderBy(a
=> a).SequenceEqual(ArrayB.OrderBy(a => a));
方法三:利用Linq方法查询交集的数据比较个数
var q = from a in ArrayA join b in ArrayB on a equals b select a; bool equals1 = ArrayA.Length == ArrayB .Length && q.Count() == ArrayA.Length;
[html] view plaincopyprint?var q = from a in ArrayA join b in ArrayB on a equals b select a; bool equals1 = ArrayA.Length == ArrayB .Length && q.Count() == ArrayA.Length; var q = from a in ArrayA
join b in ArrayB on a equals b
select a;
bool equals1 = ArrayA.Length == ArrayB .Length && q.Count() == ArrayA.Length;
方法四:泛型筛选方法中ALL
var set = new HashSet<byte>(ArrayA);
bool allThere = ArrayB.All(set.Contains);
方法五:利用数学的思想利用交集和并集的思路
bool equals3 = ArrayA.Intersect(ArrayB).Count() ==ArrayA.Union(ArrayB).Count();