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

      

+3
c #


source to share


6 answers


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

+14


source to share


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

      

+3


source to share


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(',');

      

+3


source to share


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

      

+2


source to share


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.

0


source to share


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(",,",",");

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics