具有多个条件的 Linq where 子句

2024-03-31

此方法返回通用列表,但它有多个条件来获取选择。 我只是用 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但让发生的事情变得更明智。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有多个条件的 Linq where 子句 的相关文章

随机推荐