2011-12-14 234 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;