Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate address members in C# while dealing with nulls and commas

Tags:

c#

I am trying to concatenate address lines eloquently, delimited by commas, but where a line is null, to omit the comma.

My current proposal is :

    public string fullAddress
    {
        get
        {
            return $"{address.line1 ?? ""}, {address.line2 ?? ""}, {address.line3 ?? "" } , {address.line4 ?? ""}"; 
        }

    }

But the above does not deal with the null commas. What would be a more eloquent way to achieve this?

Thanks in advance.

like image 656
SamJolly Avatar asked Dec 31 '22 20:12

SamJolly


1 Answers

I'd put the items into an array, filter the nulls out then join them.

return string.Join(", ", new[]{address.line1, address.line2, address.line3, address.line4}.Where(s => s != null));

or as suggested in the comments by @Avin Kavish:

return string.Join(", ", new[]{address.line1, address.line2, address.line3, address.line4}.Where(s => !string.isNullOrWhiteSpace(s)));
like image 138
Ousmane D. Avatar answered Feb 02 '23 19:02

Ousmane D.