views:

1221

answers:

2

Background: I have an ASP.NET MVC view page with a MultiSelectList in the View Model. I want to populate a label with the list of SelectedValues from that MultiSelectList object. The list is stored within the MultiSelectList with a type of IDName:

public class IDName {
    public int ID {get; set;}
    public string Name {get; set;}
}

So MultiSelectList.Items is an IEnumerable containing a list of IDName's. I can do a foreach over this list and grab .Name to get the name of each entry. But, I only want to do this if the ID is in MultiSelectList.SelectedItems, which appears to be a string[] and looks like:

["1", "3", "4"]

So, I want to just get the IDName.Name when IDName.ID is in the SelectedItems list.

I'm pretty new to both MVC and C# so I'm not sure the best way to do that. Any suggestions?

Update #2:

OK, I was being dense. This works:

list.Items
  .Cast<IDName>()
  .Where(x => list.SelectedValues.Cast<string>().Contains(x.ID.ToString()))

SelectedValues is actually an IEnumerable containing a string[].

+2  A: 

Try the following.

var selected = MultiSelectList.Items
  .Cast<IDName>()
  .Where(x => MultiSelectList.SelectedItems.Contains(x.Name));

What this does is process all of the items in the MultiSelectList.Items collection. It will then cast all of them to a strongly typed IDName instance. The where clause will filter the collection to only the items where the Name field matches an entry in the SelectedItems array.

JaredPar
Very close! Check out my update for the working solution (which is mainly different because I got a detail wrong in my first post). Thank you!
A: 

You can use LINQ to filter list against ids.

list.Where(item => ids.Contains(item.Id.ToString())).Select(item => item.Name)
Daniel Brückner