【问题标题】:How to concat or merge two List<Dictionary<string, object>> in c#如何在 c# 中连接或合并两个 List<Dictionary<string, object>>
【发布时间】:2022-01-13 12:46:42
【问题描述】:

我想将这个列表合并或合并为一个列表。 如何正确连接此列表?

编译器错误消息:CS0266:无法将类型“System.Collections.Generic.IEnumerable>”隐式转换为“System.Collections.Generic.List>'。存在显式转换(您是否缺少演员表?)

    List<Dictionary<string, object>> result1 = process1(); // OK
    List<Dictionary<string, object>> result2 = process2(); // OK
    List<Dictionary<string, object>> result3 = process3(); // OK
    List<Dictionary<string, object>> result4 = process4(); // OK
    List<Dictionary<string, object>> result5 = process5(); // OK
    
    var d1 = result1;

    if(result2 != null){
        d1 = d1.Concat(result2).ToList();
    }
    if(result3 != null){
        d1 = d1.Concat(result3);
    }
    if(result4 != null){
        d1 = d1.Concat(result4);
    }
    if(result5 != null){
        d1 = d1.Concat(result5);
    }

【问题讨论】:

标签: c# list dictionary merge concatenation


【解决方案1】:

问题是d1List&lt;&gt;,但你有一个Dictionary&lt;&gt;。您需要将ToList 添加到每一行

但是如果你把所有的Concat()链接在一起,最后你只需要ToList()

var empty = Enumerable.Empty<Dictionary<string, object>>()
var d1 = result1 ?? empty
    .Concat(result2 ?? empty)
    .Concat(result3 ?? empty)
    .Concat(result4 ?? empty)
    .Concat(result5 ?? empty)
    .ToList();

【讨论】:

    【解决方案2】:

    您不仅应该将 ToList() 添加到:

    d1 = d1.Concat(result2).ToList();
    

    还有下一个连接:

    if(result3 != null){
            d1 = d1.Concat(result3).ToList();
        } etc..
    

    【讨论】:

    • 非常感谢,我不相信这个问题:(
    • List> d1 = result1; if(result2 != null){ d1 = d1.Concat(result2).ToList(); } if(result3 != null){ d1 = d1.Concat(result3).ToList(); } if(result4 != null){ d1 = d1.Concat(result4).ToList(); } if(result5 != null){ d1 = d1.Concat(result5).ToList(); } 这行得通:)
    【解决方案3】:

    concat 是一个很好的运算符,但我认为如果你使用d1.AddRange(result2); 等会更好。

    您得到的错误是因为 Concat 返回 IEnumerable&lt;T&gt; 而 AddRange 运算符返回 List&lt;T&gt;

    这样可以防止使用 ToList() 运算符进行不必要的强制转换。

    【讨论】:

      猜你喜欢
      • 2013-01-28
      • 2017-09-07
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 2012-09-06
      • 1970-01-01
      相关资源
      最近更新 更多