【发布时间】:2020-03-06 19:18:17
【问题描述】:
有没有一种优雅的方法可以在 .NET 框架中使用 Linq 将一个 Dictionary 映射到另一个?
这可以通过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));
}
...但我正在寻找一些使用 LINQ 完成的方法:
// DOES NOT WORK
Dictionary<string, int> d2 =
d1.Select(kvp => {
return new KeyValuePair<string, int>(kvp.Key, int.Parse(kvp.Value));
})
【问题讨论】:
-
yourDictionary.ToDictionary(x => x.Key, x => x.Value)?
标签: c# .net linq dictionary