如何在 C# 中连接或合并两个 List<Dictionary<string, object>>

How to concat or merge two List<Dictionary<string, object>> in c#

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

编译器错误消息:CS0266:无法将类型 'System.Collections.Generic.IEnumerable<System.Collections.Generic.Dictionary<string,object>>' 隐式转换为 'System.Collections.Generic.List<System.Collections.Generic.Dictionary<string,object>>'。存在显式转换(是否缺少转换?)

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

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

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

还有下一个串联:

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

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

您得到的错误是因为 Concat returns 一个 IEnumerable<T> 而 AddRange 运算符 returns 一个 List<T>.

这样可以避免使用 ToList() 运算符进行不必要的转换。

问题是 d1 是一个 List<> 但你有一个 Dictionary<>。您需要将 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();