gpt4 book ai didi

具有多个条件的 Linq where 子句

转载 作者:行者123 更新时间:2023-12-04 14:49:45 25 4
gpt4 key购买 nike

此方法返回通用列表,但它有多个条件来获取选择。
我只是用 if - else if -else if .... 这么多 if else 我的意思是写这个
有没有更短的方法来做到这一点?谢谢你。

    public List<ProductReqNoDate> GetRequestsQuery(string departmant, int reqStateID, string firstDate, string lastDate)
{
var db = new requestsDBEntities();
var listPrn = new List<ProductReqNoDate>();
if (!string.IsNullOrEmpty(departmant))
{
return (from r in db.requests
where r.departmant== departmant
select new ProductReqNoDate
{
departmant= r.departmant,
reqNo = r.reqNo ,
reqDate = r.reqDate ,
prdctName= stringCutter((from p in db.products where p.reqNo == r.reqNo select p.prdctName).FirstOrDefault())
}).ToList();

}
if (!string.IsNullOrEmpty(firstDate) && !string.IsNullOrEmpty(lastDate))
{
DateTime dtfirstDate = Convert.ToDateTime(firstDate);
DateTime dtlastDate = Convert.ToDateTime(lastDate);
return (from r in db.requests
where r.reqDate <= dtlastDate && r.reqDate >= dtfirstDate
select new ProductReqNoDate
{
departmant= r.departmant,
reqNo = r.reqNo ,
reqDate = r.reqDate,
prdctName= stringCutter((from p in db.products where p.reqNo == r.reqNo select p.prdctName).FirstOrDefault())
}).ToList();

}
}

最佳答案

您可以将查询的核心如下:

var query = from r in db.requests 
select new ProductReqNoDate
{
departmant= r.departmant,
reqNo = r.reqNo ,
reqDate = r.reqDate ,
prdctName= stringCutter((from p in db.products
where p.reqNo == r.reqNo select p.prdctName).FirstOrDefault())
}

然后申请 if then else :
if (!string.IsNullOrEmpty(departmant))
return query.Where(r=>r.departmant== departmant).ToList();
if (!string.IsNullOrEmpty(firstDate) && !string.IsNullOrEmpty(lastDate))
{
DateTime dtfirstDate = Convert.ToDateTime(firstDate);
DateTime dtlastDate = Convert.ToDateTime(lastDate);
return query.Where(r=> r.reqDate <= dtlastDate && r.reqDate >= dtfirstDate)
.ToList();
}

它不会减少 if then else但更明智的是,会发生什么。

关于具有多个条件的 Linq where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8755176/

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