【问题标题】:Pull all duplicate keys from list of key value pairs从键值对列表中提取所有重复键
【发布时间】:2015-04-02 12:37:21
【问题描述】:

我有以下清单:

List<KeyValuePair<int, DataDetailValues>> dataResults

键值对中的键可以是重复的 - 例如列表可能包含:

Key    |    Data
1      |    ABC
2      |    DEF
3      |    GHI
1      |    JKL

我想从 dataResults 中提取键值为 1 的所有值到第二个列表中,即我想要:

 1      |    ABC
 1      |    JKL

非常感谢

【问题讨论】:

    标签: c# linq duplicates key


    【解决方案1】:

    使用Where:-

    List<KeyValuePair<int,DataDetailValues>> result = data.Where(x => x.Key == 1).ToList();
    

    【讨论】:

      【解决方案2】:

      如果您想返回任何重复项,即使它们的键值不是 1,这也可以工作。

              List<KeyValuePair<int, string>> dataResults = new List<KeyValuePair<int,string>>();
      
              dataResults.Add(new KeyValuePair<int, string>(1, "one"));
              dataResults.Add(new KeyValuePair<int, string>(2, "two"));
              dataResults.Add(new KeyValuePair<int, string>(1, "one1"));
              dataResults.Add(new KeyValuePair<int, string>(3, "three"));
              dataResults.Add(new KeyValuePair<int, string>(2, "two2"));
      
              var duplicates = dataResults.GroupBy(i => i.Key).Where(g => g.Count() > 1).Select(i => i); 
      

      【讨论】:

        猜你喜欢
        • 2019-05-17
        • 2021-02-21
        • 2021-05-26
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-27
        相关资源
        最近更新 更多