仅当字符串不为null或为空时才附加逗号

时间:2017-04-20 15:29:05

标签: c#

我在C#中创建简单的webform。在这里,我通过连接哪个效果很好来获得完整的地址。但是,如果我没有address2city等,那么我想跳过每个字符串末尾的逗号(例如,如果address1为空或空)。

string address1 = "Address1";
string address2 = "Address2";
string city = "City";
string country = "Country";
string postalCode = "00000";

string fullAddress = ? --> address1 + ","+ address2 +","+ city  and so on

6 个答案:

答案 0 :(得分:37)

如果要删除空字符串或空字符串,则必须过滤连接方法中使用的数组:

var array = new[] { address1, address2, city, country, postalCode };
string fullAddress = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));

如果我们city="",我们会Address1,Address2,Country,00000

答案 1 :(得分:5)

当一个或多个值为null或为空时,您可以使用string.joinfilter删除重复的逗号。

Console.WriteLine(string.Join(",", new string[] { address1 , address2 , city , country , postalCode }.Where(c => !string.IsNullOrEmpty(c))));

答案 2 :(得分:3)

试试这个:

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 :(得分:2)

您可以使用string.Join来完成任务。你可以run in dotnetfiddle。 请查看以下代码:

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

答案 4 :(得分:0)

您可以将所有元素放在数组中,并使用“,”将数组连接起来。在这种情况下,逗号将放置在您的不同地址部分之间。

答案 5 :(得分:0)

String.Join就是您所需要的。

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