简体   繁体   中英

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

按值对字典进行分组,并将组键映射到键列表:

input.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(_ => _.Key).ToList())

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

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM