我有两个数组(长度相同),我试图遍历两个数组中的每个元素并测试这些元素(具有相同索引)是否相等。我想得到相等的数字和不相等的数字。我已经能够使用 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/