-3

Dictionary mapItemTidsets is as follows:

Dictionary<int, List<int>> mapItemTidsets = new Dictionary<int, List<int>>();

And there are the following key and values:

Key Value

1 => 1,5,6

2 => 1,2,3,6,7

3 => 1,3,4,6

4 => 1,2,3,4,6,7

5 => 2,3,4,6,7

6 => 2,5,7

I want to specify the duplicate values in the comparison of multiple keys.

Example 1 :

Key = 1,3 => Output = (1,5,6) ∩ (1,3,4,6) = 1,6

Example 2 :

Key = 2,4,5 => Output = (1,2,3,6,7) ∩ (1,2,3,4,6,7) ∩ (2,3,4,6,7) = 2,3,6,7

solmaz ahamdi
  • 150
  • 1
  • 11

1 Answers1

2

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())
Dmytro Mukalov
  • 1,949
  • 1
  • 9
  • 14