phương thức này trả về danh sách chung nhưng nó có nhiều điều kiện để chọn. Tôi chỉ viết điều này bằng cách sử dụng if - else if -else if .... rất nhiều nếu có ý tôi là Có cách nào ngắn hơn để thực hiện việc này không? Cảm ơn bạn.LINQ trong đó khoản có nhiều điều kiện
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();
}
}
Khi LINQ được thực thi khi lần đầu tiên truy cập kết quả, có lẽ bạn có thể đặt 'từ/vị trí' đầu tiên vào var và sau đó bên ngoài ifs, sử dụng truy vấn mới chọn vào tập kết quả đã truy xuất. – Aphelion