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));
})
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With