获取两个数组的匹配数

时间:2012-06-27 06:34:19

标签: c# asp.net .net linq linq-to-objects

我有2个阵列。

String[] arrFirst={"a","b","c","d","e"};
String[] arrSecond={"a","b","f","d","g"};
String[] arrThird={"a","f","g","h","e"};

我想要arrFirstarrSecond的结果,结果是3

对于arrFirstarrThird,结果为2

我找到的所有代码都是比较两个数组并返回它们是否相同。

但我想要的是有多少匹配。

我可以循环播放。

但我认为这需要花费太多时间,我想知道是否有更快的方法。

谢谢..

3 个答案:

答案 0 :(得分:6)

您可以使用Intersect方法。

    String[] arrFirst={"a","b","c","d","e"};
    String[] arrSecond={"a","b","f","d","g"};
    String[] arrThird={"a","f","g","h","e"};

    arrFirst.Intersect(arrSecond).Count(); // 3
    arrFirst.Intersect(arrThird).Count(); //2

答案 1 :(得分:1)

arrFirst.Join(arrSecond,f=>f,s=>s,(f,s)=>f).count();

答案 2 :(得分:1)

arrFirst.Zip(arrSecond, (a, b) => a.Equals(b)).Count(a => a);