tags:

views:

50

answers:

2

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:

HolidayDates.Contains(dateTime)

Why it returns false? What's the better way to deal with contains in date?

+9  A: 

It returns false because your dateTime value has a time component, so it is a different time.

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.

James Gaunt
perfect!! Thanks!
Luís Custódio
+1  A: 

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.

Further to James's answer if you use:

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.

Ben Robinson
Another alternative for comparing date parts only would be `HolidayDates.Any(d => d.Date == dateTime.Date)`. Or, if the collection is a `List<DateTime>`, use the `Exists` method on `List<T>` itself rather than LINQ.
LukeH