将多个下拉列表选择组合为1个变量

时间:2015-10-18 23:23:02

标签: c# asp.net append

我的订单有10个下拉列表,用户可以在其中选择项目。我想将所有选定的项目组合成一个用逗号分隔的变量。我这样做的方法是为每个单独的下拉列表使用if语句并添加到字符串,这是最有效的方法吗?这是我的语法的子集(不是所有10个下拉列表),但你会明白这一点:

string fullselection = null;

if (dropdownlist1.SelectedIndex > -1) { fullselection += dropdownlist1.SelectedItem.Text; }
if (dropdownlist2.SelectedIndex > -1) { fullselection += "," + dropdownlist2.SelectedItem.Text; }
if (dropdownlist3.SelectedIndex > -1) { fullselection += "," + dropdownlist3.SelectedItem.Text; }
if (dropdownlist4.SelectedIndex > -1) { fullselection += "," + dropdownlist4.SelectedItem.Text; }
if (dropdownlist5.SelectedIndex > -1) { fullselection += "," + dropdownlist5.SelectedItem.Text; }
if (dropdownlist6.SelectedIndex > -1) { fullselection += "," + dropdownlist6.SelectedItem.Text; }

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效..

var ddlist = new List<DropdownList>();
ddlist.Add(dropdownlist1);//repeat this for all drowdowns.
var selectedTexts = ddlist.Where(x=>x.SelectedIndex > -1).Select(y=>y.SelectedItem.Text);
var fullselection = String.Join(",",selectedTexts.ToArray());