I'd like an elegant way to concatenate several columns together using LINQ, but using the + operator or concat() when any of the columns are NULL results in NULL for the value after concatenation.
Is there anything similar to concat() that handles NULL differently, or am I thinking about this in the incorrect way?
Any help is appreciated!
Here is the code I am using:
List<CustomObject> objects = (
    from obj in ObjectTable
    where obj.Id == Id
    select new CustomObject()
    {
        EnteredBy = obj.EnteredBy, 
        EntryDate = obj.EntryDate, 
        WorknoteText = 
            obj.VchWorkNote1 +
            obj.VchWorkNote2 + 
            obj.VchWorkNote3 +
            obj.VchWorkNote4 +
            obj.VchWorkNote5 +
            obj.VchWorkNote6 +
            obj.VchWorkNote7 +
            obj.VchWorkNote8 +
            obj.VchWorkNote9 +
            obj.VchWorkNote10 +
            obj.VchWorkNote11 +
            obj.VchWorkNote12 +
            obj.VchWorkNote13 +
            obj.VchWorkNote14 +
            obj.VchWorkNote15 +
            obj.VchWorkNote16 +
            obj.VchWorkNote17 +
            obj.VchWorkNote18 +
            obj.VchWorkNote19 +
            obj.VchWorkNote20
    }).ToList();
One option is to use the null coalescing operator:
List<CustomObject> objects = (from o in ObjectTable
                              where o.Id == Id
                              select new CustomObject(){
                              EnteredBy = o.EnteredBy, 
                              EntryDate = o.EntryDate, 
                              WorknoteText = 
                              (o.VchWorkNote1 ?? "") +
                              (o.VchWorkNote2 ?? "") + 
                              (o.VchWorkNote3 ?? "") +
                              (o.VchWorkNote4 ?? "") +
                              ...
                              (o.VchWorkNote20 ?? "")
                              }).ToList();
Hopefully the generated SQL will use an appropriate translation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With