将多个下拉列表选择组合成一个变量

本文关键字:一个 变量 组合 下拉列表 选择 | 更新日期: 2023-09-27 18:18:11

我有一个订单表单,其中有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; }

将多个下拉列表选择组合成一个变量

像这样的东西应该可以工作。

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