嵌套的foreach在动态创建的CheckBoxList中

时间:2012-12-19 18:33:36

标签: c# asp.net .net

我有一个动态创建的CheckBoxList。在这个CheckBoxList中,我有一个用于验证用户输入的嵌套foreach循环。用户输入他或她的电子邮件地址。用户点击提交后,即会创建CheckBoxList。如果用户的电子邮件与主题的订阅匹配,则会选中该主题旁边的复选框。我遇到的问题是将原始的foreach与嵌套的foreach相关联。

int i = 0;
foreach (Topic topic in result)
{
    string topicName = topic.TopicArn.ToString().Split(':').Last();
    ListItem li = new ListItem(topicName, topic.TopicArn);
    checkBoxList1.Items.Add(li);

    foreach (Subscription subscription in subs) // where topic equals current 
                                                // topic in original foreach?
    {
        if (txtEmail.Text == subscription.Endpoint)
            checkBoxList1.Items[i].Selected = true;
    }
    i++;
}

我在想我可能会使用LINQ为nested foreach循环添加一个条件,但我还没能把它全部拉到一起。

1 个答案:

答案 0 :(得分:1)

您必须首先创建所有复选框,然后才能开始评估是否应该选中它们。在上面的代码中,您创建一个Listitem然后循环遍历所有订阅,以便在您在复选框列表中创建第二个listitem之前它将在该循环中超出范围。

 foreach (Topic topic in result)
 {
   string topicName = topic.TopicArn.ToString().Split(':').Last();
   ListItem li = new ListItem(topicName, topic.TopicArn);
   li.Selected = subs.Any(s => s.Endpoint == txtEmail.Text && s.TopicArn == topic.TopicArn);
   checkBoxList1.Items.Add(li); 
 }
相关问题