'How to handle date range query in c#

I have a params which contains a start date and end date and then use it to query but I wanted to handle that even there is no start and enddate it will will query data. How do we handle that in c# ?

So that if there is no startDate and endDate then it will just proceed on the query.

The filteredData variable is the query. The issue right now is that when there is no startDate and endDate it will not query the data , so the solution if to handle date range if it has no value. Any idea guys ? Thanks.

#code snippet

public async Task<IPagedList<TransactionListDto>> GetList(DateTime? startDate , DateTime? endDatestring status, int id, string sortKey, string sortOrder, string searchString, int page, int pageSize, string transactionType, string repmFilter, string transactionSubType, string masterBrokerCompany, string masterBrokerName)
{
    var sortKeys = JsonConvert.DeserializeObject<List<string>>(sortKey);
    var sortOrders = JsonConvert.DeserializeObject<List<string>>(sortOrder);
    List<string> statusValues = new List<string>();
    List<string> transactionTypeValues = new List<string>();

    if (!string.IsNullOrEmpty(status))
    {
        statusValues = status.Split(',').ToList();
    }
    if (!string.IsNullOrEmpty(transactionType))
    {
        transactionTypeValues = transactionType.Split(',').ToList();
    }
    

    .......


    var filteredData = mappedData.Where(x => (masterBrokerCompanyValues.Count == 0 || masterBrokerCompanyValues.Contains(x.MasterBrokerCompany)) && x.TargetCompletionDate >= startDate && endDate <= x.TargetCompletionDate);
    var paginatedData = await AppUtil.MultipleSort<TransactionListDto>(
    filteredData.AsQueryable(), sortKeys, sortOrders).ToPagedListAsync(page, pageSize);


Solution 1:[1]

Just replace your potential null values by something that won't be limiting :

Datetime startDateForFilter = startDate ?? Datetime.Min;
Datetime endDateForFilter = endDate ?? Datetime.Max;

Solution 2:[2]

If I understand your problem correctly, if startDate and endDate are not given, your query returns an empty list.

It's probably because when you create instance of Datetime, it is automatically initialized to default value. That means, that both values are same. Try to find lowest possible date and highest possible date and set them when initialized.

Datetime startDate = DateTime.MinValue;
Datetime endDate= DateTime.MaxValue;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Seb
Solution 2 marc_s