2013-02-03 111 views
2

如何以最简洁的方式更改列表中单个项目上的单个属性?更改列表中项目的属性

public static class QuestionHelper 
    { 
     public static IEnumerable<SelectListItem> GetSecurityQuestions() 
     { 
      return new[] 
       { 
        new SelectListItem { Value = "What was your childhood nickname?", Text = "What was your childhood nickname?"}, 
        new SelectListItem { Value = "What is the name of your favorite childhood friend?", Text = "What is the name of your favorite childhood friend?"}, 
        ... 
       }; 
     } 
    } 

我要生成此列表中设置基于字符串的属性选择一个项目:

string selectText = "What is the name of your favorite childhood friend?"; 
form.SecurityQuestions = QuestionHelper.GetSecurityQuestions().Select(x => { /*Set Selected = true for SelectListItem where item.Text == selectedText */ }); 

return PartialView(form); 

注:这必须考虑到,如果(selectedText == NULL)然后设置的第一项as selected

回答

4

不要使用LINQ,使用foreach

form.SecurityQuestions = QuestionHelper.GetSecurityQuestions(); 
foreach(var item in form.SecurityQuestions) 
    item.Selected = item.Text == selectedText; 

if(selectedText == null) // Select the first item by default 
    form.SecurityQuestions.First().Selected = true; 

已创建LINQ以查询否修改对象的状态。

+0

感谢您的编辑,以前的代码看起来不正确,有2个方法调用 – parliament

相关问题