c# - 获取同一索引处相同元素的数量

标签 c# arrays linq c#-4.0

我有两个数组(长度相同),我试图遍历两个数组中的每个元素并测试这些元素(具有相同索引)是否相等。我想得到相等的数字和不相等的数字。我已经能够使用 while 循环来完成此操作,但我想知道使用 System.Linq 扩展是否有更快的方法?

这是我现在拥有的:

    var list1 = new List<Color>
        {
            Color.Aqua,
            Color.AliceBlue,
            Color.Beige,
            Color.Red,
            Color.Green,
            Color.White
        };


        var list2 = new List<Color>
        {
            Color.Red,
            Color.BurlyWood,
            Color.Beige,
            Color.Azure,
            Color.Green,
            Color.Magenta
        };

        var enumFirst = list1.GetEnumerator();
        var enumSecond = list2.GetEnumerator();

        var equal = 0;
        var notEqual = 0;

        while (enumFirst.MoveNext() && enumSecond.MoveNext())
        {
            var colorFirst = enumFirst.Current;
            var colorSecond = enumSecond.Current;

            if (colorFirst == colorSecond)
                equal++;
            else
                notEqual++;
        }

        Console.WriteLine("Elements that are equal: " + equal);
        Console.WriteLine("Elements that are not equal: " + notEqual); 

输出是:

Elements that are equal: 2
Elements that are not equal: 4

最佳答案

是的,使用 Zip

var equal = list1.Zip(list2, (l1, l2) => l1 == l2).Count(x => x);
var notEqual = list1.Count() - equal;

Zip 将跳过所有剩余的元素,如果其中一个列表没有更多的元素要枚举(列表有不同数量的元素):

If the input sequences do not have the same number of elements, the method combines elements until it reaches the end of one of the sequences.

关于c# - 获取同一索引处相同元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33798231/

相关文章:

c# - 何时在 Sqlite.Net 类上使用 Index 属性?

c - 如何在函数中编写多维数组?适合初学者的 C 编程

arrays - 为什么 Rust 在运行时检查数组边界,而(大多数)其他检查发生在编译时?

java - 如何创建一个 int 数组,其中包含给定范围内随机打乱的数字

c# - 关于 orderby 和 null 集合的 LINQ to Entities 问题

c# - 使用 LINQ 进行过滤条件搜索

c# - LINQ 到 XML 语法

c# - 有没有办法实时查看 sql server 从我的应用程序接收的查询语句?

c# - 将大量记录插入Sqlite数据库

c# - 如何改变 C# 中数字的文化?