Getting the number of items identical with the same index

I have two arrays (same length), and I'm trying to iterate each element in both arrays and check if those elements (having the same index ) are equal or not. I want to get a number equal, and a number that is not equal. I was able to do this with a loop while, but I wonder if there is a faster way with extensions System.Linq?

Here is what I have right now:

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

Output:

Elements that are equal: 2
Elements that are not equal: 4
+4
source share
2 answers

Yes, use Zip.

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

Zip , ( ):

, , .

+7

, , :

var areequal = list1.Select((x, i) => list2[i] == x);
var equals = areequal.Count(x => x);
var notequals = areequal.Count(x => !x);

Select, , , , , . , list2 , list1 ( , )

:

var areequal = list1.Take(Math.Min(list2.Count, list.Count))
                                                      .Select((x, i) => list2[i] == x);

Take , list1 , list2.

+2

Source: https://habr.com/ru/post/1616492/


All Articles