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 1:
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();