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.
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)));
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