计算linq中两个数组中相同元素的数量

时间:2012-04-11 07:03:12

标签: c# arrays linq

我有2个字符串数组:

A1: {"aa","bb","cc","dd","ee"}
A2: {"cc","dd,"ee","bla","blu"}

如何计算A1A2之间相同元素的数量(在本例中为3)?

4 个答案:

答案 0 :(得分:26)

最短的可能就是:

A1.Intersect(A2).Count()

答案 1 :(得分:2)

以下效果很好,使用列表时可能会产生更高的性能:

List<string> a1 = new List<string>() { "aa", "bb", "cc", "dd", "ee" };
List<string> a2 = new List<string>() { "cc", "dd", "ee", "bla", "blu" };

a1.Count(match => a2.Contains(match));

或(感谢@BlueVoodoo)更短的解决方案,只能稍微快一点:

a1.Count(a2.Contains);

但是这些解决方案也会重复,因此可以使用:

HashSet<string> a1 = new HashSet<string>() { "aa", "bb", "cc", "dd", "ee" };
HashSet<string> a2 = new HashSet<string>() { "cc", "dd", "ee", "bla", "blu" };

这避免了重复,因为HashSet只保留一个唯一的序列。

对上面的基准测试,HashSet与a1.Count(a2.Contains);提供最快的解决方案,即使有构建HashSet的开销。

答案 2 :(得分:2)

int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

id1.Intersect(id2).Count();

答案 3 :(得分:1)

以下代码应该诀窍

        var A1 = new[] { "aa", "bb", "cc", "dd", "ee"};
        var A2 = new[] { "cc", "dd", "ee", "bla", "blu" };

        var query = from one in A1
                    join two in A2 on one equals two
                    select one;
        var result = query.ToArray();//this should have { "cc", "dd", "ee" }