How to walk through a SelectListItem Array with Linq - techniques?
Linq – Newbie question:
string[] grades = { "2", "5", "1", "7", "4", "8", "6", "0", "9", "3" };
List<SelectListItem> xValues = new List<SelectListItem>()
{ new SelectListItem
{ Selected = true,
Text = "Select...",
Value = "Select...",
}
};
for (int a = 0; a < 10; a++)
{
xValues.Add(new SelectListItem
{ Selected = false,
Text = grades[a],
Value = grades[a]
}
);
}
My application works very fine up to this point. xValues contains now 11 elements. Each element contains a "Selected", "Text" and "Value" property. "Selected" is only in the first element set to "true". The second elements contains a "2" in "Text" and "Value", the third element contains a “5”, the fourth contains a “1” and so on...
Question: 开发者_StackOverflow中文版How to set "Selected" to "true" in that xValue element which contains a "5" in the "Text" (and in the "Value") property?
Note, that not the 6th element contains (necessarily) the searched "5"!
I believe it must be something like that:
for (int i = 0; i < ponyValues.Count(); i++)
{
xValues[i].Selected = false;
if (xValues.First().Value == “5”)
{
xValues[i].Selected = true;
}
}
Of course is ".First()" wrong... but what would be correct?
var five = xValues.FirstOrDefault(x=> x.Value == "5");
if (five != null)
five.Selected = true;
SelectListItem item = xValues.Single(item => item.Value == 5);
item.Selected = true;
Please note that this will throw an exception if there isn't exactly one item with a value of 5.
var xValues = grades.Select(g => new SelectListItem
{
Selected = (g == "5")
Text = g,
Value = g
})
.ToList();
xValues.Insert(0, new SelectListItem
{
Selected = false,
Text = "Select...",
Value = "Select...",
});
Thanks to all! Finally I do this
var isSelected = xValues.FirstOrDefault(x => x.Selected == true);
var mustBeSelected = xValues.FirstOrDefault(x => x.Value == "5");
if ((isSelected != null) && (mustBeSelected != null))
{
isSelected.Selected = false;
mustBeSelected.Selected = true;
}
because I want also to set "Selected" to "false" for the very first element. Sorry forgot to you tell this ;-)
精彩评论