Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  
like image 309
chamara Avatar asked Feb 14 '23 07:02

chamara


1 Answers

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");
like image 92
Grant Winney Avatar answered Feb 23 '23 22:02

Grant Winney