IEnumerable and string array - find matching values
Background: I have an ASP.NET MVC view page with a MultiSelectList in the view model. I want to populate a label with a SelectedValues list from this MultiSelectList object. The list is stored in a MultiSelectList with the IDName type:
public class IDName {
public int ID {get; set;}
public string Name {get; set;}
}
So MultiSelectList.Items is an IEnumerable containing a list of IDName. I can foreach over this list and grab the .Name to get the name of each entry. But I only want to do this if the ID is in MultiSelectList.SelectedItems, which looks like a string [] and looks like this:
["1", "3", "4"]
So, I just want to get IDName.Name when IDName.ID is in the SelectedItems list.
I'm new to both MVC and C #, so I'm not sure if this is the best way to do it. Any suggestions?
Update # 2:
Okay, I was tight. It works:
list.Items
.Cast<IDName>()
.Where(x => list.SelectedValues.Cast<string>().Contains(x.ID.ToString()))
SelectedValues is actually an IEnumerable containing the string [].
a source to share
Try the following.
var selected = MultiSelectList.Items
.Cast<IDName>()
.Where(x => MultiSelectList.SelectedItems.Contains(x.Name));
What this means is to process all items in the MultiSelectList.Items collection. It will then list all of them into a strongly typed instance of IDName. The where clause will filter the collection only on items where the Name field matches an entry in the SelectedItems array.
a source to share