I am creating simple webform in C#. Here I am getting full address by concatenating which works well. But let's say if I don't have address2
, city
, etc, then I want to skip appending commas at end of each string (e.g. if address1
is null or empty).
string address1 = "Address1"; string address2 = "Address2"; string city = "City"; string country = "Country"; string postalCode = "00000"; string fullAddress = ? --> address1 + ","+ address2 +","+ city and so on
When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT 'abc' + NULL yields NULL . When SET CONCAT_NULL_YIELDS_NULL is OFF, concatenating a null value with a string yields the string itself (the null value is treated as an empty string).
Concatenating with an Empty String VariableYou can use the concat() method with an empty string variable to concatenate primitive string values. By declaring a variable called totn_string as an empty string or '', you can invoke the String concat() method to concatenate primitive string values together.
The empty string is the special case where the sequence has length zero, so there are no symbols in the string. There is only one empty string, because two strings are only different if they have different lengths or a different sequence of symbols.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.
If you want to remove the empty or null string you have to filter the array used in the join method:
var array = new[] { address1, address2, city, country, postalCode }; string fullAddress = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));
If we make city=""
the we have Address1,Address2,Country,00000
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