从键值对列表中提取所有重复键

Pull all duplicate keys from list of key value pairs

我有以下列表:

List<KeyValuePair<int, DataDetailValues>> dataResults

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

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

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

 1      |    ABC
 1      |    JKL

非常感谢

使用Where:-

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

如果您想要 return 任何重复项,即使它们的键值不是 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);