woggles
woggles

Reputation: 7444

Linq to Objects DateTime Except ignore time

I have a 2 List<DateTime> and want to return the subset of the first list that isn't in the second list but ignore the time.

Is it possible to do this using the Except extension method?

var missingDates = dateList1.Except(dateList2);

Would I need to set the time in both lists to 00:00:00 or is there some way I can use the .Date property to compare?

Upvotes: 3

Views: 1115

Answers (2)

Carl Sharman
Carl Sharman

Reputation: 4845

This will ignore the time in the comparison but return the dates with times intact:

List<DateTime> missingDates = dateList1.Where(list1Item => !dateList2.Exists(list2Item => list2Item.Date == list1Item.Date)).ToList();

Upvotes: 1

Spontifixus
Spontifixus

Reputation: 6660

Try this:

var missingDates = dateList1.Select(x=>x.Date).Except(dateList2.Select(y=>y.Date));

Though this ignores the time completely, meaning that in your result the time will be missing, too...

On a second thought: You could of course implement a custom IEqualityComparer to preserve the time in the result:

public class DateComparer : IEqualityComparer<DateTime>
{
    public bool Equals(DateTime left, DateTime right)
    {
        return left.Date.Equals(right.Date);
    }

    public int GetHashCode(DateTime dateTime)
    {
        return dateTime.Date.GetHashCode();
    }
}

And then use that comparer:

var missingDates = dateList1.Except(dateList2, new DateComparer());

Upvotes: 5

Related Questions