更改列表中项目的属性

时间:2013-02-03 23:05:47

标签: c# linq

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

    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?"},
                    ...
                };
        }
    }

我想生成此列表,根据字符串将Selected属性设置为一个项目:

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

注意:这必须考虑if(selectedText == null)然后将第一项设置为Selected

1 个答案:

答案 0 :(得分: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是为了查询不修改对象的状态。

相关问题