1

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

Svirin
  • 564
  • 1
  • 7
  • 20
  • 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` – Tim Schmelter Oct 28 '20 at 09:51
  • for a sorted dictionary you can use SortedDictionary https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2?view=netcore-3.1 – user3026017 Oct 28 '20 at 09:52
  • @user3026017 The docs for `SortedDictionary` says _"Represents a collection of key/value pairs that are sorted on the key."_, whereas OP's question is asking about sorting by _value_, although that doesn't entirely seem to be what they want to do either. – ProgrammingLlama Oct 28 '20 at 09:54
  • Thanks for the replies. @Tim Schmelter , alright shall give that a try – Mr Sin6ister Oct 28 '20 at 09:55
  • what you want is to swap Keys and Values. So one Value "1" will give you the list of corresponding Keys. But as Values are not unique in the original dictionary, you have to use group by. – Drag and Drop Oct 28 '20 at 09:58

1 Answers1

3

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)));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939