Home > OS >  i have a problem when filtering a list according to two dates in c#
i have a problem when filtering a list according to two dates in c#

Time:12-12

var result = myList.Where(t =>  t.ReportDate >= StartDate)
                   .Where(t =>  t.ReportDate <= EndDate)

I'm trying to get all objects in a list (myList) thats have date (ReportDate) between StartDate and EndDate... I used the above code it worked good but when StartDate and EndDate are equals it returns null. can anyone help... thanks in advance.

CodePudding user response:

It seems, that you want to exclude time component:

var result = myList
  .Where(t => t.ReportDate.Date >= StartDate.Date &&
              t.ReportDate.Date <= EndDate.Date);

If it's your case, then when StartDate.Date == EndDate.Date you'll get result with ReportDate.Date == StartDate.Date

Please, note, that often it's more convenient to exclude the EndDate:

var result = myList
  .Where(t => t.ReportDate.Date >= StartDate.Date &&
              t.ReportDate.Date < EndDate.Date);

For instance, if we want 2021 year we can put 1.1.2021 .. 1.1.2022 instead of 1.1.2021 .. 31.12.2021

CodePudding user response:

The following sample code might put you on the right track

using System;
using System.Collections.Generic;

namespace Test
{
    class Program
    {
        static void Main()
        {
            List<DateTime> dateTimeList = new List<DateTime>
            {
                new DateTime(1946, 04, 11),
                new DateTime(1948, 04, 22),
                new DateTime(1975, 01, 23),
                new DateTime(1975, 01, 23),
                new DateTime(1977, 07, 07),
                new DateTime(1988, 05, 02),
            };
            DateTime beginDate = new DateTime(1970, 01, 01);
            DateTime endDate = new DateTime(1979, 12, 31);
            List<DateTime> result = dateTimeList.FindAll(x => x >= beginDate && x <= endDate);
            foreach (DateTime dateTime in result)
                Console.WriteLine(dateTime);
        }

    }
}

CodePudding user response:

I've done my best to incorporate your comments. This will ignore the time portion of the dates and will work with null ReportDates.

    DateTime now = DateTime.Now;
    // Get the Date part for the variables before the linq query
    DateTime startDate = now.Date;
    DateTime endDate = now.Date;
    
    List<Report> myList = new List<Report> { new Report(1, now), new Report(2, null), new Report(3, now.AddDays(1)) };

    // You are not required to make multiple Where calls
    // Check that ReportDate has a value before comparison
    // Get the Date part for the comparisons
    var reports = myList.Where(t => t.ReportDate.HasValue
                               && t.ReportDate.Value.Date >= startDate
                               && t.ReportDate.Value.Date <= endDate);
    
    foreach (var report in reports)
    {
        Console.WriteLine($"Report {report.ReportId}");
    }

Report 1

  • Related