Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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();
                List<Dictionary<string, object>> 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();         } This is worked :)
– Deniz Taş
                Jan 13, 2022 at 13:06

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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.