Unable to cast object of type WhereListIterator<system.web.Mvc.ListItem> to type system.web.mvc.listitem

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'.


--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.


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();

I assume the SelectList lets you select more than 1 item?

So SelectedValue is probably a list? Not 1 listitem.

Cast it to:

 WhereListIterator<ListItem> selected = (WhereListIterator<ListItem>)searchBag.Qualities.SelectedValue;

instead and see what properties you have there.

SelectedValue is not a ListItem, it's the value of the selected list item. So given this:

var selectList = new SelectList(companiesList, "Id", "Name", companiesList[3]);

selectList.SelectedValue will equal companiesList[3].Id. If you want the actual list item you can do something like this:

ListItem selected = selectList.GetListItems().Where(x => x.Value == selectList.SelectedValue.ToString())

Just curious, why do you want the selected list item?

Need Your Help

Google Maps geocoding Multiple Lines Point Limitation

javascript google-maps geocoding polyline

With the help of this great website I have been able to get about 92% of what I need, but I just can't get over the hump on this thing. I made a map that geocodes multiple points and draws a line