你可以使用如下方法
IEnumerable<int> GetDuplicates(IDictionary<int, List<int>> dict, IEnumerable<int> keysToLook)
{
return dict.Keys
.Intersect(keysToLook)
.SelectMany(k => dict[k])
.GroupBy(i => i)
.Where(g => g.Count() == keysToLook.Count())
.Select(g => g.Key)
.ToArray();
}
通过指定的一组键在字典中查找重复项。
测试验证:
static void Tests()
{
var dict = new Dictionary<int, List<int>>()
{
{ 1, new[] { 1, 5, 6 }.ToList() },
{ 2, new[] { 1, 2, 3, 6, 7 }.ToList()},
{ 3, new[] { 1, 3, 4, 6 }.ToList()},
{ 4, new[] { 1, 2, 3, 4, 6, 7 }.ToList()},
{ 5, new[] { 2, 3, 4, 6, 7 }.ToList()},
{ 6, new[] { 2, 5, 7 }.ToList()}
};
var expected1 = new[] { 1, 6 };
var expected2 = new[] { 2, 3, 6, 7 };
var result1 = GetDuplicates(dict, new[] { 1, 3 });
var result2 = GetDuplicates(dict, new[] { 2, 4, 5 });
Console.WriteLine(expected1.SequenceEqual(result1));
Console.WriteLine(expected2.SequenceEqual(result2));
}
更新:结果也可以用更简单的linq形式来实现:
IEnumerable<int> GetDuplicates(IDictionary<int, IEnumerable<int>> dict, IEnumerable<int> keysToLook)
{
return dict.Keys
.Intersect(keysToLook)
.Select(k => dict[k])
.Aggregate((p, n) => p.Intersect(n));
}
字典具有更通用的专业化(值的类型表示为IEnumerable<T> 而不是List<T>)。但是,如果字典中仍需要 List<T>,则应修改聚合以显式使用 List:
.Aggregate((p, n) => p.Intersect(n).ToList())