我有一个构建地址字段的循环,其中一些字段可能在字符串的末尾为空
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)
您还应该避免在您的情况下使用字符串,而是使用StringBuilder.避免使用感知格式 - 只需列表[iRow]是一个更好的选择.
尝试这样的事情:
string result = string.Join(", ",
list.Where(s => !string.IsNullOrEmpty(s)).ToArray());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11409 次 |
最近记录: |