how to check null before linq concat list c# RRS feed

  • Question

  • User-1256377279 posted

    Hi Guys,

    I have 3 list object and want to join using concat, but how to check nulls before it concat.

    Below is my code.

      nonmandat.RelatedAuthorities = nonmandat.RelatedPersons.Concat(nonmandat.RelatedFamilies.DefaultIfEmpty())

    From above code if RelatedPersons or RelatedFamilies or RelatedCorporateBodies is null how to avoid concating.



    Friday, February 22, 2019 11:39 AM

All replies

  • User753101303 posted


    You are sure it happens ? It's common to use lists which are not null but empty. I expect concatenating  empty lists should work (it should just left the source list unchanged).

    I wonder if the problem couldn't be that you are using mistalkenly DefaulfEmpty. For example with :

    var a = new List<string> { "a", "b" };
    var b = new List<string>();

    var c = a.Concat(b); will be the same than a that is "a","b"

    var c = a.Concat(b.DefaultIfEmpty()); is "a","b", null because with DefaultIfEmpty you asked to return a singleton list with the default value for its element type (and the default value for a string is null)

    var c = a.Concat(b.DefaultIfEmpty("z")); would return the "a", "b", "z" list.

    So in short I wonder if you don't want to ,just use :


    Friday, February 22, 2019 4:19 PM