【问题标题】:Find duplicate values in dictionary of list c# [closed]在列表c#的字典中查找重复值[关闭]
【发布时间】:2019-04-12 16:10:13
【问题描述】:

字典mapItemTidsets如下:

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

还有以下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

我想在多个键的比较中指定重复值。

示例 1:

键 = 1,3 => 输出 = (1,5,6) ∩ (1,3,4,6) = 1,6

示例 2:

键 = 2,4,5 => 输出 = (1,2,3,6,7) ∩ (1,2,3,4,6,7) ∩ (2,3,4,6,7 ) = 2,3,6,7

【问题讨论】:

标签: c# linq dictionary


【解决方案1】:

你可以使用如下方法

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&lt;T&gt; 而不是List&lt;T&gt;)。但是,如果字典中仍需要 List&lt;T&gt;,则应修改聚合以显式使用 List

.Aggregate((p, n) => p.Intersect(n).ToList())

【讨论】:

  • 输出不正确,我用这个命令:List&lt;int&gt; B = new List&lt;int&gt;(); B.Add(2); B.Add(4); B.Add(5); IEnumerable&lt;int&gt; x = GetDuplicates(mapItemTidsets, B); 但是X中得到的输出等于:1,2,3,6,7,4
  • @solmazahamdi,是的,修复了代码。
  • 感谢您的努力。但是输出仍然不正确。输出为:1,3,6
  • @solmazahamdi,它适用于哪个组合键?
  • 你是对的,感谢您的耐心和回复
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2018-10-15
  • 2019-01-15
  • 2023-01-07
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多