How can I change a single property on a single item in a list in the most succinct way?
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?"},
...
};
}
}
I want to generate this list set the Selected property one item based on a string:
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);
Note: This has to account for if(selectedText == null) then set the first item as Selected
Don’t do it with LINQ, do it with
foreach!LINQ has been created for querying no to modify the state of an object.