【问题标题】:Filter a Dictionary<String,List<String>>过滤字典<String,List<String>>
【发布时间】:2019-03-06 16:20:16
【问题描述】:

我有一个Dictionary&lt;String, List&lt;String&gt;&gt;,我需要过滤它,并且只留下那些List&lt;String&gt; 包含重复(重复)值的对。我知道应该有一个 linq 子查询,但我的所有变体都失败了。

例子:

var dictionary = new Dictionary<String,List<String>>();

dictionary.Add("Key1", new List<String>{"1","2","2","3"});
dictionary.Add("Key2", new List<String>{"1","2","3"});
dictionary.Add("Key3", new List<String>{"1","2","4"});
dictionary.Add("Key4", new List<String>{"1","2","5"});

所以我只需要留下第一对,因为该列表有重复值“2”。

【问题讨论】:

  • 您可能希望提供示例输入和预期输出数据。很难判断重复项是在单个列表中还是跨列表。
  • @JohnMcCann 谢谢你的建议。
  • 您可以使用 distinct 创建另一个列表,然后将您的列表与它进行比较以排除匹配的行..

标签: c# list linq dictionary


【解决方案1】:

你的字典:

  • 获取所有键值对
  • 其中,仅取删除重复项后的列表不再具有相同数量的元素(因此存在 个重复项)
  • 然后从剩余的键值对创建一个新字典

代码:

var filteredDictionary = dictionary.Where(pair => pair.Value.Distinct().Count()
                                               != pair.Value.Count)
                                   .ToDictionary(x => x.Key, x => x.Value);

【讨论】:

  • 我喜欢你的方法。我试图将 GroupBy 与 Count() > 1 一起使用。您的解决方案更简单。
  • 非常感谢您!现在我更好地理解了 linq 逻辑
猜你喜欢
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多