【问题标题】:compare two identical lists of strings比较两个相同的字符串列表
【发布时间】:2011-12-14 16:30:33
【问题描述】:

假设我有以下代码:

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

    if (numbers.Equals(numbers2))
    {

    }

如您所见,我有两个包含相同项目的列表。有没有办法用一种方法检查这两个列表是否相等?

解决方案:

使用SequenceEqual()

谢谢

【问题讨论】:

  • 是否应该考虑序列项位置?
  • @Ozkan 如果您有重复项怎么办?像numbers: { 1, 1, 2}numbers2: { 1, 2 } 你会认为它们是平等的吗?
  • @Matthew Cox,嗨,这被认为不会发生。但我发现它的方法是SequenceEqual()
  • 如果您只想“比较两个相同的字符串列表”,那么return true 将完成这项工作。也是最快的解决方案

标签: c# asp.net linq list


【解决方案1】:

使用Enumerable.SequenceEqual,但首先使用Sort 列表。

【讨论】:

    【解决方案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;
    

    【讨论】:

    • 这就是我的答案。只取决于重复是否重要。如果他们这样做,那么这将返回误报。
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多