participant
participant

Reputation: 3003

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"}} ... });

Upvotes: 2

Views: 1192

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109537

How about this?

var result = 
    dict.ToLookup(x => x.Value, x => x.Key)
    .ToDictionary(y => y.Key, y => y.ToList());

Although I don't see why you couldn't just use the result from dict.ToLookup() without changing it to a dictionary, for example:

var dict = new Dictionary<string, int>
{
    {"One", 1},
    {"Two", 2},
    {"1", 1},
    {"TWO", 2},
    {"ii", 2}
};

var test = dict.ToLookup(x => x.Value, x => x.Key);

Console.WriteLine(string.Join(", ", test[2])); // Prints: Two, TWO, ii

Upvotes: 2

Auneell
Auneell

Reputation: 81

You can use Linq to achieve.

    private static Dictionary<int, List<string>> Transform(Dictionary<string, int> input)
    {
        var result = new Dictionary<int, List<string>>();
        foreach (var value in input.Select(x => x.Value).Distinct())
        {
            var lst = input.Where(x => x.Value == value).Select(x => x.Key).ToList();
            result.Add(value, lst);
        }
        return result;
    }

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

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())

Upvotes: 5

Related Questions