gpt4 book ai didi

c# - Linq 添加动态 where 子句

转载 作者:行者123 更新时间:2023-11-30 20:17:42 26 4
gpt4 key购买 nike

我正在尝试将动态 where 子句添加到我的 linq 代码中。但是我收到以下错误。其他示例提供了相同的代码,但它们工作正常,所以我不确定我是否遗漏了什么。

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

错误:

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?)

请帮忙

最佳答案

您忘记调用 .ToList()最后为了得到一个 List<T>这是 toBeReturn 的类型变量:

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

此外,我建议您反转逻辑,以便在 sname 时过滤 SQL 服务器上的结果。变量具有值(value)。在您当前的实现中,您从表中获取所有记录,然后在内存中过滤它们,这不是最有效的方法。

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

关于c# - Linq 添加动态 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43841016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com