gpt4 book ai didi

c# - 更改列表中项目的属性

转载 作者:行者123 更新时间:2023-11-30 21:00:50 25 4
gpt4 key购买 nike

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

    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) then set the first item as Selected

最佳答案

不要用 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 已创建用于查询 no 以修改对象的状态。

关于c# - 更改列表中项目的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14678418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com