I have a action in MVC controller
public ActionResult ExportExcel(string ReportType,DateTime? FromDate,DateTime? ToDate)
{
var query = UnitOfWork.RepoTestResAnalysis.GetAll();
var QueryData = query.Where(s => s.MSO == ms && (FromDate != null && (s.TEST_DATE.Value >= FromDate)) && (ToDate!=null && (s.TEST_DATE.Value<=ToDate))).ToList();
}
Now If FromDate
and ToDate
are null then I am getting QueryData
Count is Zero. But I need all records. So Can anyone tell me how can I get expected result. While FromDate
& ToDate
has value then I am getting expected result.
According to the information you have provided
Change you below statement:
var QueryData = query.Where(s => s.MSO == ms && (FromDate != null && (s.TEST_DATE.Value >= FromDate)) && (ToDate!=null && (s.TEST_DATE.Value<=ToDate))).ToList();
To
var QueryData = query.Where(s => s.MSO == ms && (FromDate == null || (s.TEST_DATE.Value >= FromDate)) && (ToDate == null || (s.TEST_DATE.Value<=ToDate))).ToList();
If the FromDate
Or ToDate
will be equal to NULL
, it won't check them against s.TEST_DATE.Value
.
You can do it like below also: Change QueryData assignment to:
var QueryData = query.Where(s => s.MSO == ms &&
(s.TEST_DATE.Value >= (FromDate ?? DateTime.MinValue)) &&
(s.TEST_DATE.Value <= (ToDate ?? DateTime.MaxValue))).ToList();
I know it's an old question, but I will be glad if my code can help anybody. I think following implementation will be the short and easy to read:
public ActionResult SomeMethod(string ReportType, DateTime? FromDate, DateTime? ToDate)
{
var query = UnitOfWork.RepoTestResAnalysis.GetAll();
var QueryData = query.Where(x => x.DateField >= (FromDate ?? x.DateField) && x.DateField <= (ToDate ?? x.DateField).ToList();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.