如何通过GroupBy迭代 - 获取重复键错误

时间:2014-08-19 18:28:05

标签: c#

我无法弄清楚如何做到这一点。我希望能够迭代这本词典,因为它是我的单元测试,因此对我来说每一对都很重要

var invalidPageNumberAndSize = new Dictionary<string, string>
{
    {"0", ""},
    {"", "0"},
    {"abc", ""},
    {"", "abc"}
}.GroupBy(p => p.Key);

foreach (var invalidPagingCombination in invalidPageNumberAndSize)
{

    Console.WriteLine(invalidPagingCombination.Key + " " + invalidPagingCombination);
}

2 个答案:

答案 0 :(得分:0)

您在字典中输入两个空的键:

 {"", "0"},

 {"", "abc"}

将此更改为

{"foo", "abc"}

并且错误将消失。字典每个键只能有1个实例。如果需要,您还可以使用元组列表:

var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>("", "apple"));
list.Add(new Tuple<string, string>("", "zebra"));

答案 1 :(得分:0)

使用KeyValuePair的集合代替字典:

var invalidPageNumberAndSize = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("0", ""),
    new KeyValuePair<string, string>("", "0"),
    new KeyValuePair<string, string>("abc", ""),
    new KeyValuePair<string, string>("", "abc")
}.GroupBy(p => p.Key);