我正在使用这个linq查询检查所有6个下拉列表中是否有重复的选择。
要做到这一点,目前我正在为所有下拉列表将SelectedIndex设置为0。而不是那样,我想要那两个下拉列表.SelectedIndex = 0具有相同的SelectedValue。
var allIndexes = new List<int>
{
drpdwnlst_Seq1.SelectedIndex,
drpdwnlst_Seq2.SelectedIndex,
drpdwnlst_Seq3.SelectedIndex,
drpdwnlst_Seq4.SelectedIndex,
drpdwnlst_Seq5.SelectedIndex,
drpdwnlst_Seq6.SelectedIndex
};
var noSelectedIndexIsTheSame = allIndexes.Where(x => x != 0)
.GroupBy(x => x)
.All(x => x.Count() == 1);
if (!noSelectedIndexIsTheSame)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AdminUserError", "alert('Selection Rrepeated.'); ", true);
drpdwnlst_Seq1.SelectedIndex = 0;
drpdwnlst_Seq2.SelectedIndex = 0;
drpdwnlst_Seq3.SelectedIndex = 0;
drpdwnlst_Seq4.SelectedIndex = 0;
drpdwnlst_Seq5.SelectedIndex = 0;
drpdwnlst_Seq6.SelectedIndex = 0;
}
答案 0 :(得分:1)
您可以将List更改为以下定义(因此您可以保留大部分逻辑)
List<KeyValuePair<DropDownList, int>> allIndexes = new List<KeyValuePair<DropDownList, int>>
{
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq1, drpdwnlst_Seq1.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq2, drpdwnlst_Seq2.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq3, drpdwnlst_Seq3.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq4, drpdwnlst_Seq4.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq5, drpdwnlst_Seq5.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq6, drpdwnlst_Seq6.SelectedIndex)
};
var groups = allIndexes.Where(x => x.Value != 0).GroupBy(x => x.Value);
boolean noSelectedIndexIsTheSame = groups.All(g => g.Count() == 1);
if (!noSelectedIndexIsTheSame)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AdminUserError", "alert('Selection Rrepeated.'); ", true);
foreach (var g in groups)
{
if (g.Count() == 1)
{
continue;
}
foreach (var kvp in g)
{
kvp.Key.SelectedIndex = 0;
}
}
}
这样,你有你的组合框的引用+当前选择的索引,你按KeyValuePair.Value分组,如果没有索引是相同的,你有一个单独的bool检查。如果是,它将循环组,如果每组发现超过1,重置那些