【发布时间】:2012-04-23 11:42:39
【问题描述】:
我有 2 个字符串数组:
A1: {"aa","bb","cc","dd","ee"}
A2: {"cc","dd,"ee","bla","blu"}
如何计算A1 和A2 之间相同元素的数量(在本例中为 3)?
【问题讨论】:
-
如果其中一个数组中有重复项,您希望发生什么?
-
我希望他们算作 1 场比赛
我有 2 个字符串数组:
A1: {"aa","bb","cc","dd","ee"}
A2: {"cc","dd,"ee","bla","blu"}
如何计算A1 和A2 之间相同元素的数量(在本例中为 3)?
【问题讨论】:
最短的可能是这样的:
A1.Intersect(A2).Count()
【讨论】:
Count Contains 方法是否正确? (见提问者的澄清评论)
以下效果很好,使用列表时可能会产生更高的性能:
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 的开销。
【讨论】:
int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };
id1.Intersect(id2).Count();
【讨论】:
下面的代码应该可以解决问题
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" }
【讨论】: