Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map one dictionary to another using Linq

Is there an elegant way to map one Dictionary to another using Linq in the .NET framework?

This can be accomplished via enumerating with foreach:

var d1 = new Dictionary<string, string>() {
    { "One", "1" },
    { "Two", "2" }
};

// map dictionary 1 to dictionary 2 without LINQ
var d2 = new Dictionary<string, int>();
foreach(var kvp in d1) {
    d2.Add(kvp.Value, int.Parse(kvp.Value));
}

...but I'm looking for some way to accomplish with LINQ:

// DOES NOT WORK
Dictionary<string, int> d2 =
    d1.Select(kvp => {
        return new KeyValuePair<string, int>(kvp.Key, int.Parse(kvp.Value));
    })
like image 520
Aaron Thomas Avatar asked Dec 30 '25 22:12

Aaron Thomas


2 Answers

Just use ToDictionary extension method from System.Linq namespace

var d2 = d1.ToDictionary(kvp => kvp.Key, kvp => int.Parse(kvp.Value));

Since Dictionary<TKey, TValue> class implements IEnumerable<KeyValuePair<TKey,TValue>> and ToDictionary is extension method for IEnumerable<T> the code above works fine

like image 84
Pavel Anikhouski Avatar answered Jan 01 '26 14:01

Pavel Anikhouski


Please try this:

var d1 = new Dictionary<string, string>() {
    { "One", "1" },
    { "Two", "2" }
};

// map dictionary 1 to dictionary 2 with LINQ
var d2 = d1.ToDictionary(kvp => kvp.Value, kvp => int.Parse(kvp.Value));
like image 23
sam Avatar answered Jan 01 '26 14:01

sam