Reputation: 22914
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
Upvotes: 2
Views: 5434
Reputation: 13022
Don't do it with LINQ, do it with 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 has been created for querying no to modify the state of an object.
Upvotes: 4