Reputation: 12437
I have 2 lists containing different types. One is a string[]
and another is a List<SelectListItem>
.
SelectListItem
(it's in mvc):
public string Text {get;set;}
public string Value {get;set;}
public bool Selected {get;set;}
My string[]
is just contains some text values.
What i'm trying to do is, get whatever is in the string[]
, then set "Selected = true"
for whatever Value
matches, and "Selected = false"
for what doesnt match.
So lets say my string[]
is:
Test1
Test2
Test3
And my List<SelectListItem>
is:
new SelectListItem { Text = "Testing", Value = "Test1", Selected = false },
new SelectListItem { Text = "Testing", Value = "Test4", Selected = true }
In the above List<SelectListItem>
, i have one match. So what i'd like to do, is set Selected = true for that particular entry so that i end up with:
new SelectListItem { Text = "Testing", Value = "Test1", Selected = true },
new SelectListItem { Text = "Testing", Value = "Test4", Selected = false }
How would I achieve this?
Upvotes: 3
Views: 2738
Reputation: 48558
How about
list.ForEach(x => x.Selected = stringarray.Contains(x.Value))
Upvotes: 1
Reputation: 4907
var items = SelectListItems.Where(p=>stringArray.Contains(p));;
foreach(var item in items)
item.Selected=true;
Upvotes: 0
Reputation: 116448
foreach(var i in selectListItemList)
i.Selected = stringArray.Contains(i.Value);
or using List.ForEach
:
selectListItemList.ForEach(i => i.Selected = stringArray.Contains(i.Value));
Upvotes: 2