List< DateTime>上的Any()方法;不能按预期工作 [英] Any() method on List<DateTime> doesn't work as per expectation
问题描述
我正在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");
输出:
推荐答案
dateTimeList
中的项目属性不等于dateNow
的Ticks
和TimeOfDay
属性,并且dateNow
具有更多的刻度比您的dateTimeList
中的那个.您需要添加以下行:
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);
这将使dateNow
的Ticks
和TimeOfDay
属性等于您添加到dateTimeList
的属性.
This will make the Ticks
and TimeOfDay
properties of your dateNow
equals to ones that you've added to your dateTimeList
.
这篇关于List< DateTime>上的Any()方法;不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!