How to merge multiple List values in one list - Getting Error as Value cannot be null RRS feed

  • Question

  • User-1024101449 posted

    How to merge multiple list values in one list values.

    For example,

    List<string> List1 = new List<string> {"A","B","C"}; // Some times null value also

    List <string> List2 = new List<string> {"D","E","F"}; // Some times null value also

    List <string> List3=  null;  // Some times null value also

    My Query is below :

     List<string> ArrAllValue = List1.Concat(List2.Concat(List3))
                                                                   .Where(x => !string.IsNullOrEmpty(x)) //probably

    Error : Value Cannot be null

    Wednesday, August 30, 2017 8:57 AM


  • User-1508012637 posted

    Hi gani7787,

    The error indicates that the Concat() method does not allow the sequences to be null. So the first solution is that you could use the ternary expression to check the current list. If it is null, give it an empty list:

    List<string> ArrAllValue = (List1 == null ? new List<string>() : List1)
                                .Concat((List2 == null ? new List<string>() : List2)
                                .Concat(List3 == null ? new List<string>() : List3)).ToList();

    The second is that you could initialize the list object with an empty list instead of null:

    List<string> List123 = new List<string>();

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 31, 2017 3:16 AM