JGeZau JGeZau - 3 months ago 22
C# Question

How to update SelectListItem Selected value inside a List<T>

I have a

List<SelectListItem>
that holds campuses and each
SelectListItem.Text
is the name of the campus and
SelectListItem.Value
is the campus id.

Then I have
List<string>
that holds some campuses ids.

I need to set the
Selected
property of the
SelectListItem
to
true
to all of the campuses that match a campus id in here
List<string>


My code below only works if there is only one id in
List<string>


List<SelectListItem> CampusesList = ...
...
List<string> campuses = GetCampusesIds(id);
foreach (string campus in campuses) {
CampusesList.ForEach(x => { x.Selected = x.Value == campus; });
}


How can I solve this?

Thanks

Answer

You can use the List.Contains Method (T) to return true if a specific value is in that list.

CampusesList.ForEach(x => x.Selected = campuses.Contains(x.Value));
Comments