[C#]Compare two string Arrays

[C#]Compare two string Arrays


以下说明如何比较2个字符串数组是否相同,

如下的范例,准备array1, array2, array3, array4


string[] array1 = new string[] { "Data", "Account", "credit", "Debit" }; 
string[] array2 = new string[] { "Data1", "Account1", "credit", "Debit" }; 
string[] array3 = new string[] { "Account", "credit", "Debit", "Data"};
string[] array4 = new string[] { "Data", "Account", "credit", "Debit" }; 

1.使用LINQ来比较(找出相同的数量,然后比较数量。数量相同表示2个字符串数组是相同的),


bool isarray12thesame = ((from item in array1 where array2.Contains(item) 
                          select item).Count() == array1.Length); //false
bool isarray13thesame = ((from item in array1 where array3.Contains(item) 
                          select item).Count() == array1.Length); //true
bool isarray14thesame = ((from item in array1 where array4.Contains(item) 
                          select item).Count() == array1.Length); //true

2.看到其他人提到可以使用SequenceEqual,在这里记录一下!


bool isarray12thesame = array1.SequenceEqual(array2); //false
bool isarray13thesame = array1.SequenceEqual(array3); //false
bool isarray14thesame = array1.SequenceEqual(array4); //true

只是SequenceEqual是比较同一个位罝,如果整个数据都相同(如上面的array1与array4相比),但位置不同的话(如上面的array1与array3相比),就不能用SequenceEqual了!

3.使用Except方式(感谢91提供)


bool isarray12thesame = (array1.Except(array2).Count() == 0); //false
bool isarray13thesame = (array1.Except(array3).Count() == 0); //true
bool isarray14thesame = (array1.Except(array4).Count() == 0); //true

参考数据:

Compare two string Arrays