List< DateTime>上的Any()方法;不能按预期工作 [英] Any() method on List<DateTime> doesn't work as per expectation

查看:101
本文介绍了List< DateTime>上的Any()方法;不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Winforms中使用.net 4.6(此处的代码来自测试控制台应用程序)

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

有一次我有一个DateTime列表,我需要弄清楚该列表是否包含特定日期.

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

为此,我尝试在列表上使用Any(). 即使列表中确实包含所需的日期,Any()也仅返回false.

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");

输出:

推荐答案

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);

这将使dateNowTicksTimeOfDay属性等于您添加到dateTimeList的属性.

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

这篇关于List&lt; DateTime&gt;上的Any()方法;不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆