计算2个数组包含相等元素的位置

Dor*_*ork 2 c# linq enumerable where

我有2 arrays个相同的长度,我需要计算他们的位置有多少包含相同的元素.我做了这个功能,但我觉得可以在不创建的情况下完成tuple.有没有更广泛和简单的方法来做到这一点?

static int GetCoincidence(int[] a, int[] b)
{
    return a.Zip(b, Tuple.Create).Where(x => x.Item1 == x.Item2).Select(x => 1).Sum();
}
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 5

没有替代方案Tuple(我试图保留你的想法Sum):

  int[] a = new int[] { 1, 2, 3, 4, 4, 5, 9};
  int[] b = new int[] { 7, 8, 3, 4, 4, 8};

  int count = a
    .Zip(b, (left, right) => left == right ? 1 : 0)
    .Sum();
Run Code Online (Sandbox Code Playgroud)

  • 这比当前接受的答案(没有引入封闭)和原始(没有元组分配)更好.LINQ令人遗憾的是,人们倾向于使用随机选择的变量名称(如`x`,`y`,`z`,`zz`等)选择*看起来简洁的答案,并将所有内容放在一行中.我很确定你是否像其他答案一样复制/粘贴了函数定义,并写入`return a.Zip(b,(x,y)=> x == y?1:0).Sum();`会得到更多的喜欢(甚至接受:) (2认同)