[英]Why my IEnumerable of dates doesn't contains my date
I've a list of brazilian Holidays, so I got this: 我有一份巴西假期清单,所以我得到了这个:
[0] {01/01/2010 00:00:00} System.DateTime
[1] {16/02/2010 00:00:00} System.DateTime
[2] {02/04/2010 00:00:00} System.DateTime
[3] {04/04/2010 00:00:00} System.DateTime
[4] {21/04/2010 00:00:00} System.DateTime
[5] {01/05/2010 00:00:00} System.DateTime
[6] {03/06/2010 00:00:00} System.DateTime
[7] {07/09/2010 00:00:00} System.DateTime
[8] {12/10/2010 00:00:00} System.DateTime
[9] {02/11/2010 00:00:00} System.DateTime
[10]{15/11/2010 00:00:00} System.DateTime
[11]{25/12/2010 00:00:00} System.DateTime
And when in a method I receive dateTime = {03/06/2010 19:00:00}
and call: 在一个方法中,我收到
dateTime = {03/06/2010 19:00:00}
并致电:
HolidayDates.Contains(dateTime)
Why it returns false? 为什么它返回false? What's the better way to deal with contains in date?
处理日期的更好方法是什么?
It returns false because your dateTime value has a time component, so it is a different time. 它返回false,因为你的dateTime值有一个时间组件,所以它是一个不同的时间。
To strip out the time component call 去除时间组件调用
HolidayDates.Contains(dateTime.Date)
Provided you always store the dates in your IEnumerable with 00:00:00 as the time component then this will work. 如果您始终将IEnumerable中的日期存储在00:00:00作为时间组件,那么这将起作用。
The collection does not have that value in it. 该集合中没有该值。 There is a matching date, but your time is 19:00 whereas the time in the collection is 00:00.
匹配日期,但您的时间是19:00,而集合中的时间是00:00。
Further to James's answer if you use: 如果您使用以下内容,请继续James的回答:
HolidayDates.Select(d => d.Date).Contains(dateTime.Date)
It will not matter if there is a time component in the items in the collection. 如果集合中的项目中存在时间组件,则无关紧要。 It will always compare the date part only.
它总是只比较日期部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.