Search code examples
c#listdictionarygroupingkeyvaluepair

How to copy/transfer key and values from 1 dictionary to another new dictionary/list?


I am a beginner to the Key-Value manipulation. I currently have 2 dictionaries.First dictionary with the original key and value.

var firstDict = new Dictionary<string, int>();
  • key:a ,value: 1
  • key:b ,value: 2
  • key:c ,value: 1
  • key:d ,value: 3
  • key:e ,value: 5
  • key:f ,value: 1
  • key:g ,value: 4
  • key:h ,value: 2
  • key:i ,value: 1
  • key:j ,value: 2

And below is my second dictionary.

Dictionary<int, string> secondDict = firstDict
         .GroupBy(k => k.Value)
         .ToDictionary(g => g.Key, g => string.Join(",", g.Select(k => k.Key)));

This is what second dictionary prints.

  • key 1 : values : a,c,f,i
  • key 2 : values : b,h,j ...

So what I want to do now is to separate each key-value(s) from the second dictionary and create dynamic dictionaries/lists to store them if they satisfy some conditions if(kv.Value > 3){store in new Dictionary}

Key_1_Dict

a,c,f,i

Key_2_Dict

b,h,j

Key_3_Dict ......

May I know if there is a way to do that ?


Solution

  • If I have understood your point, you can use Where to filter data:

    Dictionary<int, string> secondDict = firstDict.Where(x => x.Value > 3)
    .GroupBy(k => k.Value)
    .ToDictionary(g => g.Key, g => string.Join(",", g.Select(k => k.Key)));
    

    Update

    For the Third dictionary:

    Dictionary<int, string> thirdDict = secondDict
    .Where(x => x.Value.Split(',').Length > 2 && x.Value.Split(',').Length <= 4)
    .ToDictionary(g => g.Key, g => g.Value);