2011-12-14 173 views
1

兩個相同的名單比方說,我有以下代碼:比較字符串

List<string> numbers = new List<string> { "1", "2" }; 
    List<string> numbers2 = new List<string> { "1", "2"}; 

    if (numbers.Equals(numbers2)) 
    { 

    } 

就像你可以看到我有相同的物品兩份名單。有沒有辦法通過使用一種方法來檢查這兩個列表是否相等?

SOLUTION:

使用SequenceEqual()

感謝

+1

請參閱http://stackoverflow.com/questions/1546925/comparing-two-liststring-for-equality – dash 2011-12-14 16:31:28

+0

是否應考慮序列項目的位置? – sll 2011-12-14 16:32:56

回答

2
// if order does not matter 
bool theSame = numbers.Except(numbers2).Count() == 0; 

// if order is matter 
var set = new HashSet<string>(numbers); 
set.SymmetricExceptWith(numbers2); 
bool theSame = set.Count == 0;