Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append commas only if strings are not null or empty

Tags:

c#

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 
like image 537
sgl Avatar asked Apr 20 '17 15:04

sgl


People also ask

How do you concatenate null values in a string in SQL?

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

Can you concat 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.

Why do we use empty strings?

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.

What is string concat in C#?

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.


1 Answers

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

like image 107
Alessandro D'Andria Avatar answered Oct 18 '22 15:10

Alessandro D'Andria