C# 如何将两个 List<String> 相互比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9602579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:04:54  来源:igfitidea点击:

How to compare two List<String> to each other?

c#.net

提问by Developer

Let's say there are

假设有

List<string> a1 = new List<string>();

List<string> a2 = new List<string>();

Is there way to do like this?

有没有办法做到这一点?

if (a1 == a2) 
{

}

采纳答案by Mark Byers

If you want to check that the elements inside the list are equal and in the same order, you can use SequenceEqual:

如果要检查列表中的元素是否相等且顺序相同,可以使用SequenceEqual

if (a1.SequenceEqual(a2))

See it working online: ideone

在线查看:ideone

回答by Tim Schmelter

You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:

您还可以使用except(产生两个序列的集合差)来检查是否存在差异:

IEnumerable<string> difference = a1.Except(a2);
if(!difference.Any()){}

回答by Sai Kalyan Kumar Akshinthala

You can check in all the below ways for a List

您可以通过以下所有方式查看列表

List<string> FilteredList = new List<string>();
//Comparing the two lists and gettings common elements.
FilteredList = a1.Intersect(a2, StringComparer.OrdinalIgnoreCase);

回答by JYelton

I discovered that SequenceEqualis not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

我发现这SequenceEqual不是比较两个字符串列表的最有效方法(最初来自http://www.dotnetperls.com/sequenceequal)。

I wanted to test this myself so I created two methods:

我想自己测试一下,所以我创建了两种方法:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

第二种方法是我遇到的一些代码,想知道是否可以重构为“更易于阅读”。(并且还想知道 LINQ 优化是否会更快。)

As it turns out, with two lists containing 32k strings, over 100 executions:

事实证明,有两个包含 32k 个字符串的列表,执行了 100 多次:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks
  • 方法 1 平均需要 6761.8 个滴答
  • 方法 2 平均需要 3268.4 个滴答

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

为了简洁、性能和代码可读性,我通常更喜欢 LINQ;但在这种情况下,我认为基于循环的方法是首选。

Edit:

编辑:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

我使用优化的代码重新编译,并运行了 1000 次迭代的测试。结果仍然有利于循环(更是如此):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks
  • 方法 1 平均需要 4227.2 个滴答
  • 方法 2 平均需要 1831.9 个滴答

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

在 Core i7-920 上使用 Visual Studio 2010、C# .NET 4 Client Profile 进行测试

回答by Sunil Thakur

    private static bool CompareDictionaries(IDictionary<string, IEnumerable<string>> dict1, IDictionary<string, IEnumerable<string>> dict2)
    {
        if (dict1.Count != dict2.Count)
        {
            return false;
        }

        var keyDiff = dict1.Keys.Except(dict2.Keys);
        if (keyDiff.Any())
        {
            return false;
        }

        return (from key in dict1.Keys 
                let value1 = dict1[key] 
                let value2 = dict2[key] 
                select value1.Except(value2)).All(diffInValues => !diffInValues.Any());
    }