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:

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With