简单的愚蠢的foreach循环问题

时间:2010-03-30 06:24:44

标签: c#

在下面的代码中,我试图阅读所选项目的列表和所有可用项目的列表。

我想存储所有未从所有项目列表中选择的项目。但是使用下面的代码,我有所有项目的列表......在哪里以及如何打破第二个循环,包括projectId.Value == selectedProjectId.Value?

public IEnumerable NotselectedProjects;         public IEnumerable NotSelectedProjects()         {

        if (this.NotselectedProjects == null)
        {
            List<SelectListItem> result = new List<SelectListItem>();
            foreach (var selectedProjectId in selectedProjects) 
            {
                foreach (var projectId in projectLists)
                {
                    if (projectId.Value != selectedProjectId.Value)
                    {
                        result.Add(new SelectListItem
                        {
                            Selected = false,
                            Text = projectId.Text,
                            Value = projectId.Value
                        });
                        this.NotselectedProjects = result.AsEnumerable();
                    }
                }
            }
        }
        return this.NotselectedProjects;

    }

3 个答案:

答案 0 :(得分:5)

您可以使用LINQ将循环缩短为

var result = from projectId in projectLists
             where !selectedProjects.Any(s => s.Value == projectId.Value)
             select new SelectListItem  
                        {  
                            Selected = false,  
                            Text = projectId.Text,  
                            Value = projectId.Value  
                        });

答案 1 :(得分:2)

为什么不在其他情况下添加休息时间?

if (projectId.Value != selectedProjectId.Value)
{
    ...
}
else 
{
    break;
}

答案 2 :(得分:0)

if(this.NotSelectedProjects == null) {
//build a dictionary for fast look-up
Dictionary<string, SelectListItem> selectedProjects = new Dictionary<string, SelectListItem>();
foreach(SelectListItem item in selectedProjectes){
    selectedProjects.Add(item.Value, SelectListItem);
}

//loop through all the projects
List<SelectItem> result = new List<SelectListItem>();
foreach(SelectListItem item in projectlist) {
    if(selectedProjects.HasKey(item.Value)){
        continue; //this project is selected
    }

    result.Add(item);
}

this.NotSelectedProjects = result;
}

return this.NotSelectedProjects;