chamara
chamara

Reputation: 12709

How to filter SelectList with linq

I tried to filter the SelectList with where clause but i get the following error.

Unable to cast object of type 'WhereEnumerableIterator`1[System.Web.Mvc.SelectListItem]' to type 'System.Web.Mvc.SelectList'.

public SelectList ReadDocumentHeaderTypeList()
{
    using (context = new Pinc_DBEntities())
    {
        List<SelectListItem> seList =
            (from tb in context.tblDocumentHeaderTypes
            select new SelectListItem
            {
                Value = SqlFunctions.StringConvert((double)tb.DocumentHeaderTypeID).Trim(),
                Text = tb.DocumentHeaderTypeDescription,
            }).OrderBy(o => o.Text).ToList();
        SelectList slist = new SelectList(seList, "Value", "Text");
        return slist;
    }
}

SelectList sl = (SelectList)rep.ReadDocumentHeaderTypeList().Where(o => o.Value == "5" && o.Value == "6");//Error occurs here  

Upvotes: 4

Views: 9334

Answers (2)

Grant Winney
Grant Winney

Reputation: 66511

Your SelectList appears to contain a list of SelectListItem objects. I'm not sure what it looks like internally, but you had to supply the list of items to the new instance of SelectList. I assume you'll have to do that again.

... = new SelectList(rep.ReadDocumentHeaderTypeList()
                        .Where(o => o.Value == "5" || o.Value == "6").ToList(),
                     "Value", "Text");

Upvotes: 7

mlorbetske
mlorbetske

Reputation: 5659

Change this:

SelectList sl = (SelectList)rep.ReadDocumentHeaderTypeList().Where(o => o.Value == "5" && o.Value == "6");

to this:

SelectList sl = new SelectList(rep.ReadDocumentHeaderTypeList().Where(o => o.Value == "5" && o.Value == "6"));

The issue is exactly what the compiler is telling you, that the result of the Where is not a SelectList. The solution is to make one from the result.

Also, note that your where clause checks that Value is equal to 5 and equal to 6 which will always be false (assuming Value is string)

Documentation on the SelectList constructor

Upvotes: 3

Related Questions