Search code examples
c#listdictionarymergeconcatenation

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


I want merge or concat this list for one list. How to concat this list without errors ?

Compiler Error Message: CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.Dictionary<string,object>>' to 'System.Collections.Generic.List<System.Collections.Generic.Dictionary<string,object>>'. An explicit conversion exists (are you missing a cast?)

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

Solution

  • You should add ToList() not only to :

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

    but also to next concatenations:

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