如果您确定每个项目在每个数组中只出现一次,您可以将它们连接在一起并获取计数,例如:
var arrs = new[] { arr1, arr2, arr3, arr4, arr5, arr6 };
var intermediate = arrs.SelectMany(a => a)
.GroupBy(x => x)
.Select(g => new { g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count);
var maxCount = intermediate.First().Count;
var results = intermediate.TakeWhile(x => x.Count == maxCount);
或者,如果您更喜欢查询语法,那就是:
var arrs = new[] { arr1, arr2, arr3, arr4, arr5, arr6 };
var intermediate =
from a in arrs.SelectMany(a => a)
group a by a into g
orderby g.Count() descending
select new { g.Key, Count = g.Count() };
var maxCount = intermediate.First().Count;
var results = intermediate.TakeWhile(x => x.Count == maxCount);
结果集将包含 3 个项目:
Key, Count
"A", 4
"B", 4
"D", 4
更新
鉴于您更新的问题,这样的事情应该有效:
var items = arrs.SelectMany(a => a).Distinct();
var pairs =
from a in items
from b in items
where a.CompareTo(b) < 0
select new { a, b };
var results =
(from arr in arrs
from p in pairs
where arr.Contains(p.a) && arr.Contains(p.b)
group arr by p into g
orderby g.Count() descending
select g.Key)
.First();
这里的逻辑是:
- 首先在任何数组中找到所有不同的项目
- 然后找到每一对要搜索的项目
- 获取每一对,按包含该对的数组列表分组
- 按包含每对的数组数量按组排序,降序
- 返回第一对