简体   繁体   中英

Linq add dynamic where clause

Im trying to add a dynamic where clause to my linq code. But I am getting the following error. Other samples gives the same code but they are working fine so im not sure if i missed something.

var toBeReturn = db.estimate.ToList();
if(sname != null)
{
    toBeReturn =  toBeReturn.Where(x => x.estimate_status == sname);
}

Error:

Severity Code Description Project File Line Suppression State Error CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

Help please

You forgot to call .ToList() at the end in order to get a List<T> which is the type of the toBeReturn variable:

toBeReturn =  toBeReturn.Where(x => x.estimate_status == sname).ToList();

Also I would recommend you inverting your logic so that you filter the results on the SQL server if the sname variable has value. In your current implementation, you are fetching all records from the table and then filter them in-memory which is not the most efficient approach.

var toBeReturn = (sname != null) 
    ? db.estimate.Where(x => x.estimate_status == sname).ToList()
    : db.estimate.ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM