[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