環境:數組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: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();