【问题标题】:Map one dictionary to another using Linq使用 Linq 将一个字典映射到另一个字典
【发布时间】: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 =&gt; x.Key, x =&gt; x.Value) ?

标签: c# .net linq dictionary


【解决方案1】:

只需使用来自System.Linq 命名空间的ToDictionary 扩展方法

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

由于Dictionary&lt;TKey, TValue&gt; 类实现了IEnumerable&lt;KeyValuePair&lt;TKey,TValue&gt;&gt;ToDictionaryIEnumerable&lt;T&gt; 的扩展方法,所以上面的代码可以正常工作

【讨论】:

    【解决方案2】:

    请试试这个:

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

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 1970-01-01
      • 2021-06-22
      • 2017-07-07
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      相关资源
      最近更新 更多