You can use method as follows
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();
}
to find duplicates in dictionary by specified set of keys to look.
Test to verify:
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));
}
Update: The result can also be achieved with bit simpler form of 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));
}
where the dictionary has more generic specialization (the type of values is denoted as IEnumerable<T>
instead of List<T>
). If List<T>
however is still required inside the dictionary, the aggregation should be modified to work explicitly with List
:
.Aggregate((p, n) => p.Intersect(n).ToList())