从字符串末尾删除多个char类型

Adr*_*der 10 c# string

我有一个构建地址字段的循环,其中一些字段可能在字符串的末尾为空

List<string> list = new List<string>();

//list can contain any number of values, some of which might be "" (empty string)

string returnValue = "";
for (int iRow = 1; iRow <= list.Count; iRow++)
    returnValue += String.Format("{0}, ", list[iRow]);

returnValue = returnValue.Trim();
Run Code Online (Sandbox Code Playgroud)

我的输出是

asd, aaa, qwe, 123123, , , , , 
Run Code Online (Sandbox Code Playgroud)

如何从字符串中删除尾随","?

Aka*_*ava 26

returnValue = returnValue.TrimEnd(' ', ',');
Run Code Online (Sandbox Code Playgroud)

  • TrimEnd上的参数是一个ParamArray,你不需要新的char [] - returnValue = returnValue.TrimEnd('',','); (2认同)

Mih*_*kic 8

您还应该避免在您的情况下使用字符串,而是使用StringBuilder.避免使用感知格式 - 只需列表[iRow]是一个更好的选择.

尝试这样的事情:

string result = string.Join(", ", 
                  list.Where(s => !string.IsNullOrEmpty(s)).ToArray());
Run Code Online (Sandbox Code Playgroud)