【问题标题】:Calculate how much positions of 2 arrays contain equal elements计算2个数组有多少位置包含相等的元素
【发布时间】:2023-03-10 01:42:01
【问题描述】:

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

【问题讨论】:

  • .Where(x => x.Item1 == x.Item2).Select(x => 1).Sum() 等价于.Count(x => x.Item1 == x.Item2)。你比你需要的更冗长。但你的版本没有错。

标签: c# linq where enumerable


【解决方案1】:
var common = (from elemA in a.Select((x, y) => new { Value = x, Index = y })
                     join elemB in b.Select((x, y) => new { Value = x, Index = y })
                     on new { elemA.Index, elemA.Value } equals new { elemB.Index, elemB.Value }
                     select elemA).ToList();

【讨论】:

    【解决方案2】:

    没有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();
    

    【讨论】:

    • 这比当前接受的答案(没有引入闭包)和原始答案(没有元组分配)要好。 LINQ 的可悲之处在于,人们倾向于使用随机选择的变量名称(如 xyzzz 等)选择看起来简洁的答案,并将所有内容放在一个单线。我很确定如果您只是像其他答案一样复制/粘贴函数定义并在return a.Zip(b, (x, y) => x == y ? 1 : 0).Sum(); 中写入会得到更多喜欢(甚至接受:)
    【解决方案3】:

    这个怎么样:

    static int GetCoincidence(int[] a, int[] b)
    {
        return a.Where((x,i)=>x==b[i]).Count();
    }
    

    试试这个Example用法:

    int[] a= {1,2,3,4,55,6,77,7,8,9};
    int[] b= {1,2,3,4,34,5,79,7,8,9};
    Console.WriteLine(GetCoincidence(a,b));
    // Output will be 7
    

    【讨论】:

    • 您可以将.Where((x,i)=>x==b[i]).Count() 压缩为.Count((x,i)=>x==b[i])。次要细节,但人们似乎经常忘记 Count 已经包含 Where 的功能:)
    • @Flater: 不,这是不可能的,因为Count() 不支持第二个参数i,你可以试一试,如果我错了,请告诉我?
    • 你是对的; Count 没有可能的第二个参数。这似乎违反直觉,因为 Select 和 Where 都可以选择。但无论如何,你是对的。
    【解决方案4】:

    你可以使用LINQ 除了这个。 以下是如何做到这一点的示例:

    public static int GetCoincidence(int[] a, int[] b)
    {
        return a.Count()-a.Except(b).Count();
    }
    

    【讨论】:

    • 这不会考虑序列中元素的顺序,因为 OP 似乎想要。
    • @PeterDuniho 哦,是的,你说得对,我没有注意到有问题
    【解决方案5】:

    恕我直言,由于使用 Zip() 创建所需的并行枚举,您的解决方案相当优雅。另一种方法是自己显式管理IEnumerator<T> 对象,这并不漂亮。

    我要做的一项更改是使用Count() 而不是Where()Select()Sum()

    static int GetCoincidence(int[] a, int[] b)
    {
        return a.Zip(b, Tuple.Create).Count(x => x.Item1 == x.Item2);
    }
    

    请注意,使用这种方法,您可以使用任何 IEnumerable<T> 实现来实现目标,而不仅仅是数组。如果您对使用 only 数组感到满意,您可以使用提供索引的Where() 重载,如this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2014-10-18
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多