Search code examples
c#listdictionarykeyvaluepair

How to get same values from different keys in a Dictionary?


Newbie Alert: I'm very new to using Dictionary or anything related to KeyValuePair.
I have a Dictionary and I added some values to it.

var first_choice_dict = new Dictionary<string, int>();
The names are the keys and the numbers are value which indicates their choices.

Bob, 2
Chad, 1
Dan, 3
Eden, 5
Fred, 1
Greg, 4
Hope, 2
Ivan, 1
Jim, 2

May I please know if there is a way to sort them by the values that are same and then move only the keys to a new dictionary(or with the values also should be fine), as seen below:

Sorted:

Abe,1
Chad,1
Fred,1
Ivan, 1
......

New Dictionary of Choice 1:
Abe,Chad,Fred,Ivan


Solution

  • You don't want to "sort" them at all. You want to group by the value and then build a new dictionary where the choice is the key, as value i'd suggest IEnumerable<string>

    Dictionary<int, IEnumerable<string>> choiceDict = userChoicesDict
        .GroupBy(kv => kv.Value)
        .ToDictionary(g => g.Key, g => g.Select(kv => kv.Key));
    

    If you instead want a string as value with the comma separated names:

    Dictionary<int, string> choiceDict = userChoicesDict
        .GroupBy(kv => kv.Value)
        .ToDictionary(g => g.Key, g => string.Join(",", g.Select(kv => kv.Key)));