从选定的DropDownList值中仅删除最后一个逗号

时间:2018-02-22 11:09:51

标签: c# asp.net

我从两个DropDownList中选择值,我的条件是仅删除列表中的最后一个逗号(将DropDownList转换为List)。这是一个老问题,我知道但是陷入了一个简单的问题。这是我到目前为止所尝试的:

var ddlAll = new List<DropDownList>() //Lists of DropDownList
{
   ddl1, //DropDownList 1
   ddl2  //DropDownList 2
};

foreach(var item in ddlAll) //Iterating through for loop
{
   lblShow.Text += "'" + item.SelectedValue + "'" + ", ".TrimEnd(',', ' '); //Getting the values here and trying to remove the last comma
}

使用上面的代码,我得到以下输出:

'Hello 2''Hello 4'

但我的预期输出如下:

'Hello 2', 'Hello 4'

没有TrimEnd(),我明白了:

'Hello 2', 'Hello 4',

N.B:可能会有更多DropDownList个值但它应该只删除它们中的最后一个逗号。

3 个答案:

答案 0 :(得分:1)

你在每次迭代中都在做string text = ""; foreach(var item in ddlAll) { text += "'" + item.SelectedValue + "'" + ", "; } lblShow.Text = text.TrimEnd(',', ' '); 。最后,您必须更改代码才能执行此操作。例如:

"'" + item.SelectedValue + "'" + ", ".TrimEnd(',', ' ');

另外,我会改写这个:

string.Format

使用string.Format("'{0}',", item.SelectedValue); 进入:

$"'{item.SelectedValue}',";

甚至,如果您使用的是C#6或更高版本,请执行以下操作:

NULL

答案 1 :(得分:0)

只需使用String.Join

String.Join(",", new List<string> { "Hello 2", "Hello 4" })

在您的情况下,第二个参数是

ddlAll.Select(x => x.SelectedValue)

答案 2 :(得分:0)

executors
相关问题