-6

I need to compare keys if they are +10 or +20 and group them before output.

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

Expected Output:

Keys: 6000 - 6030
      apple
      pear
      papaya

Keys: 6060
      banana

Keys: 6090
      guava

This is my code but I get an error:

string firstKeyVal;
string lastKeyVal;

foreach (KeyValuePair<string, string> kvp in Dict)
{
    while(kvp.Key = kvp.Key +10 || kvp.Key + 20)
    {
        lastKeyVal = (kvp + 1).key;
    }
}
Timo Salomäki
  • 7,099
  • 3
  • 25
  • 40
Manick9
  • 137
  • 2
  • 10
  • 7
    You do not seem familiar with the C# language at all. I would suggest you at least get the basics before trying to implement anything -- you will save time. – Frédéric Hamidi Sep 13 '16 at 09:15
  • I am having trouble with writing the while loop. I am a beginner and havent learnt C# formally before.I know there are a few syntax error and need help to fix it. – Manick9 Sep 13 '16 at 09:21
  • Have a look at this question (http://stackoverflow.com/questions/39361077/groupby-of-listdouble-with-tolerance-doesnt-work/39361541#39361541) which does something similar for doubles with a tolerance. – MakePeaceGreatAgain Sep 13 '16 at 09:21
  • "a few syntax error"? First I see: `while(kvp.Key = kvp.Key +10 || kvp.Key + 20)` should be `while(kvp.Key == kvp.Key +10 || kvp.Key == kvp.Key + 20)`. This would be syntactically correct, but semantically non-sense, a value can´t be equal its value +10. – MakePeaceGreatAgain Sep 13 '16 at 09:24
  • 1
    I think he meant `while(kvp.Key == lastKeyVal.Key +10 || kvp.Key == lastKeyVal.Key + 20)` but the way he's assigning and even its name even, is incorrect. (should be nextKeyVal, and `(kvp + 1).key;` is not the way to obtain the next pair in the dictionary). – Keyur PATEL Sep 13 '16 at 09:28
  • Thanks @KeyurPATEL. Thats what I meant and I could not find this syntax nextKeyVal. – Manick9 Sep 13 '16 at 09:33
  • _This is my code but **I get an error**_ - Do we have to beg for you to tell us what the error is? – Chris Dunaway Sep 13 '16 at 15:18

1 Answers1

2

Here is a approach with GroupBy

Dictionary:

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

Grouping:

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;
});
fubo
  • 44,811
  • 17
  • 103
  • 137