bla*_*ist 6 linq where conditional-statements
此方法返回通用列表,但它有多个条件来获取选择.我只是写这个使用if - else if -else if ....如果这么多,我的意思是否有更短的方法来做到这一点?谢谢.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将查询的核心如下所示:
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())
}
Run Code Online (Sandbox Code Playgroud)
然后申请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();
}
Run Code Online (Sandbox Code Playgroud)
它不会降低,if then else但会更加明智,会发生什么.
1*
你可以找到更好的解决方案,但我希望这个帮助(我的事情)但我使用它:你可以测试这个功能
List<ProductReqNoDate> yourList = GetRequestsQuery(string departmant, int reqStateID)
if (!string.IsNullOrEmpty(firstDate) && !string.IsNullOrEmpty(lastDate))
{
yourdatagrid.Itemsource = yourList.where(a=> a.reqDate <= Datetime.parse(firstDate) & a.reqDate >= Datetime.parse(lastDate))
}
public List<ProductReqNoDate> GetRequestsQuery(string departmant, int reqStateID)
{
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();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以应用第一个列表中的任何条件,但不建议在大量应用程序或数据库中的许多信息中应用。
2*
或者您可以只指定第一个日期和最后一个日期;例如,如果未设置日期,则使第一个日期 = 01/01/1900 和最后一个日期 Datetime.Today 并始终在 linq 查询中传递您的日期