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

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.

Answers


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

Having trouble with LINQ left join on List<FileInfo>

c# linq

I have two List&lt;FileInfo&gt; lists, SourceFiles and DestFiles. I want to build a LINQ query that will return a list of the items whose filenames are in Source but not in Dest, i.e. a left join....

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.