Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat strings in LINQ while properly dealing with NULL values

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();
like image 288
CircusNinja Avatar asked Nov 30 '22 17:11

CircusNinja


1 Answers

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.

like image 140
Jon Skeet Avatar answered Dec 05 '22 11:12

Jon Skeet