Asp.net-mvc – Unable to cast object of type WhereListIterator to type system.web.mvc.listitem

asp.net-mvc

I have a SelectList that I first check for a selected value != null and then want to use this selectedvalue in a where clause for a filter. Like so:

if(searchBag.Qualities.SelectedValue != null){
    ListItem selected = (ListItem)searchBag.Qualities.SelectedValue;
}

I made the cast in a seperate useless line to pinpoint the problem.
This gives me a

Unable to cast object of type 'WhereListIterator`1[System.Web.Mvc.ListItem]' to type 'System.Web.Mvc.ListItem'.

Weuh?

–EDIT–
It was indeed because multiple selections were made.
This was because on creation I set the selected value to theItems.Where(i=>i.someCriterea) and I forgot to put .FirstOrDefault() at the end. Ending up in the possibility of multiple answers.
Since it was an IEnumerable, it was a lazy list and hence the WhereListIterator I guess.
I solved it by simple putting FirstOrDefault at the end.

Best Solution

Its already been explained, but here's another suggestion as to how to get what you're looking for:

if(searchBag.Qualities.SelectedValue != null){
    ListItem selected = (ListItem)searchBag.Qualities.SelectedValue.FirstOrDefault();
}
Related Question