Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any() method on List<DateTime> doesn't work as per expectation

I m working on .net 4.6 in winforms (here code is from test console application)

At one point I'm having a list of DateTime and I need to figure out if this list contains specific date or not.

For that I m trying use Any() on the list. Even if the list does contain the desired date, Any() returns false only.

Following is example code, which also have same behavior. So if I can get any idea on this code, I guess it will help on my real code too.

List<DateTime> dateTimeList = new List<DateTime>();
DateTime dateNow = DateTime.Now;

DateTime date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, dateNow.Hour, dateNow.Minute, 00);
date = date.AddMinutes(-10);
while (date < dateNow.AddMinutes(10))
{
    dateTimeList.Add(date);
    date = date.AddMinutes(1);
}

dateNow = dateNow.AddSeconds(-dateNow.Second);
dateNow = dateNow.AddMilliseconds(-dateNow.Millisecond);

foreach (DateTime dateInList in dateTimeList)
    Console.WriteLine("date list List:" + dateInList.ToString("ddMMyyyy hh:mm:ss:fffz") + " - VS - desired date:" + dateNow.ToString("ddMMyyyy hh:mm:ss:fffz"));

if (dateTimeList.Any(x => x == dateNow))
    Console.WriteLine("date found");
else
    Console.WriteLine("date Not found");

if (dateTimeList.Any(x => x.ToString("ddMMyyyy hh:mm:ss:fffz") == dateNow.ToString("ddMMyyyy hh:mm:ss:fffz")))
    Console.WriteLine("date string matched");
else
    Console.WriteLine("date string didn't match");

output:

enter image description here

like image 933
Amit Avatar asked Mar 08 '18 06:03

Amit


1 Answers

The Ticks and TimeOfDay properties of items in your dateTimeList is not equal to Ticks and TimeOfDay properties of your dateNow, and dateNow has more ticks than the one in your dateTimeList. You need to add this line:

dateNow = new DateTime(dateNow.Year, dateNow.Month,
           dateNow.Day, dateNow.Hour, dateNow.Minute, 00);

This will make the Ticks and TimeOfDay properties of your dateNow equals to ones that you've added to your dateTimeList.

like image 137
Salah Akbari Avatar answered Oct 09 '22 05:10

Salah Akbari