neildt
neildt

Reputation: 5362

Compare two List<DateTime> in C#

I've the following code;

'list of dates
List<DateTime> oAllDates = new List<DateTime>();

// Imagine we are adding DateTime objects with the following values.
oAllDates.Add("2013-11-01"); 
oAllDates.Add("2013-11-02"); 
oAllDates.Add("2013-11-03"); 
...
oAllDates.Add("2013-11-30"); 

List<DateTime> MyDates = new List<DateTime>();
MyDates.Add("2013-11-03");

I want to get a bool result if any date in MyDates appears in the list oAllDates. I could use the following

foreach (DateTime dtDate in oAllDates)
{
    foreach (DateTime myDate in MyDates)
    {
        ...
    }
}

Is there a better way using LINQ that could achieve this. Also, I then have a list like

List<int> MyDaysByName = new List<int>();
MyDaysByName.Add(1); //sunday
MyDaysByName.Add(5); //thursday

I'm wanting to find any dates in oAllDates that are a Sunday or Thursday ?

Upvotes: 0

Views: 4722

Answers (3)

Ofir
Ofir

Reputation: 5319

Use Intersect

bool result = oldDates.Intersect(MyDates).Any();

Upvotes: 3

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

oAllDates.Any(x => MyDates.Contains(x));

Upvotes: 1

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

You can use Intersect

var anyOfthem = oAllDates.Intersect(MyDates).Any();

Upvotes: 7

Related Questions