C#键值对:while循环中的键比较

时间:2016-09-13 09:13:59

标签: c#

我需要比较键,如果它们是+10或+20,并在输出之前将它们分组。

 Keys  Value
 6000  apple
 6010  pear
 6030  papaya
 6060  banana
 6090  guava

预期产出:

Keys: 6000 - 6030
      apple
      pear
      papaya

Keys: 6060
      banana

Keys: 6090
      guava

这是我的代码但我收到错误:

string firstKeyVal;
string lastKeyVal;

foreach (KeyValuePair<string, string> kvp in Dict)
{
    while(kvp.Key = kvp.Key +10 || kvp.Key + 20)
    {
        lastKeyVal = (kvp + 1).key;
    }
}

1 个答案:

答案 0 :(得分:2)

以下是GroupBy的方法

字典:

Dictionary<int, string> dict = new Dictionary<int, string>() { { 6000, "apple" }, { 6010, "pear" }, { 6030, "papaya" }, { 6060, "banana" }, { 6090, "guava" } };

分组:

int group = 0, prev = 0;
var result = dict.GroupBy(x =>
{
    if (!((prev + 20) == x.Key || (prev + 10) == x.Key))
    {
        group++;
    }
    prev = x.Key;
    return group;
});