如何将两个List 相互比较? [重复]

时间:2022-01-22 12:46:48

This question already has an answer here:

这个问题在这里已有答案:

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) 
{

}

5 个解决方案

#1


97  

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

#2


8  

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()){}

#3


8  

I discovered that SequenceEqual is 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
  • 方法1平均得到6761.8个滴答
  • Method 2 took an average of 3268.4 ticks
  • 方法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
  • 方法1平均采用4227.2个滴答
  • Method 2 took an average of 1831.9 ticks
  • 方法2平均采用1831.9滴答

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

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

#4


0  

    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());
    }

#5


-3  

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);

#1


97  

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

#2


8  

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()){}

#3


8  

I discovered that SequenceEqual is 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
  • 方法1平均得到6761.8个滴答
  • Method 2 took an average of 3268.4 ticks
  • 方法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
  • 方法1平均采用4227.2个滴答
  • Method 2 took an average of 1831.9 ticks
  • 方法2平均采用1831.9滴答

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

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

#4


0  

    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());
    }

#5


-3  

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);