Possible Duplicate:
Comparing two List<string> for equality
How can I find out whether two arrays of string are equal to each other?
I used this, but it does not work, even though the contents of both are the same.
string[] array1 = new string[]{"A" , "B"}
string[] array2 = new string[]{"A" , "B"}
if(a开发者_开发技巧rray1 == array2) // it return false !!!!
{
//
}
If you have access to Linq, use SequenceEqual. Otherwise, simply provide the code to first check if the arrays are equal length, and then if items are equal at each index.
Have a look at the following on StackOverflow. I believe what you are looking for is the following. Comparing arrays in C#
var arraysAreEqual = Enumerable.SequenceEqual(array1, array2);
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;
}
You can use the .NET4 feature Array.IStructuralEquatable.Equals like this:
IStructuralEquatable equ = array1;
bool areEqual = equ.Equals(array2, EqualityComparer<string>.Default);
This can also be written on one line:
bool areEqual = (array1 as IStructuralEquatable).Equals(array2, EqualityComparer<string>.Default);
Using IStructuralEquatable has the advantage of allowing a custom comparer to be used.
加载中,请稍侯......
精彩评论