Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform Dictionary<string, int> to Dictionary<int, List<string>>

Q How can I most efficiently convert a Dictionary<string, int> to a Dictionary<int, List<string>>?

Example

var input = new Dictionary<string, int>() { {"A", 1}, {"B", 1}, {"C", 2} ...
Dictionary<int, List<string>> result = Transform(input)
Assert.IsTrue(result, { {1, {"A", "B"}}, {2, {"C"}} ... });
like image 463
participant Avatar asked Jan 23 '26 20:01

participant


1 Answers

Group the dictionary by values and map the group keys to list of keys:

input.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(_ => _.Key).ToList())
like image 178
Selman Genç Avatar answered Jan 26 '26 12:01

Selman Genç