Add commas only if strings are not null or empty
I am creating a simple web form in C #. Here I am getting the full address by concatenating, which works well. But let's say if I have not address2
, city
etc., then I want to skip the extra commas at the end of each line (for example if address1
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
If you want to remove an empty or empty string, you need 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 do city=""
, we haveAddress1,Address2,Country,00000
you can use string.join along with filter to remove duplicate commas when one or more values are null or empty.
Console.WriteLine(string.Join(",", new string[] { address1 , address2 , city , country , postalCode }.Where(c => !string.IsNullOrEmpty(c))));
Try the following:
string address1 = "Address1";
string address2 = "Address2";
string city = "";
string country = "Country";
string postalCode = "00000";
Func<string, string> f = s => string.IsNullOrEmpty(s) ? string.Empty : string.Format("{0},", s);
string fullAddress = string.Format("{0}{1}{2}{3}{4}", f(address1), f(address2), f(city), f(country), f(postalCode)).Trim(',');
You can use string.Join
to accomplish your task. You can run at dotnetfiddle . Please check the code below:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
string address1 = "Address1";
string address2 = "Address2";
string city = "City";
string country = "Country";
string postalCode = "00000";
List<string> strArray = new List<string> { address1, address2, city, country, postalCode };
string fullAddress = string.Join(",", strArray.Where(m=> !string.IsNullOrEmpty(m)).ToList());
Console.WriteLine(fullAddress);
}
}
You can put all your elements in an array and join the array with ",". In this case, the commas will be well placed, between your other address part.
String.Join is what you need.
string address1 = "Address1";
string address2 = "Address2";
string city = "City";
string country = "Country";
string postalCode = "00000";
string[] stuff = new string [] { address1, address2, city, country, postalCode };
string fulladdress = string.Join(",", stuff).Replace(",,",",");