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

Time:01-13

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

CodePudding user response:

The problem is that d1 is a List<> but you have a Dictionary<>. You would need to add ToList to each line

But if you chain all the Concat() together, you only need ToList() at the end:

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

CodePudding user response:

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..

CodePudding user response:

Concat is a fine operator, but I think it is better if you use d1.AddRange(result2); etc.

The error you get is because the Concat returns an IEnumerable<T> while the AddRange operator returns a List<T>.

This way you prevent an unnecessary amount of casting with the ToList() operator.

  •  Tags:  
  • Related