比较C#中的两个List <DateTime>

nei*_*ldt 0 c# linq datetime compare list

我有以下代码;

'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");
Run Code Online (Sandbox Code Playgroud)

如果MyDates中的任何日期出现在列表oAllDates中,我想得到一个bool结果.我可以使用以下内容

foreach (DateTime dtDate in oAllDates)
{
    foreach (DateTime myDate in MyDates)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法使用LINQ来实现这一目标.此外,我有一个列表,如

List<int> MyDaysByName = new List<int>();
MyDaysByName.Add(1); //sunday
MyDaysByName.Add(5); //thursday
Run Code Online (Sandbox Code Playgroud)

我想在周日或周四的oAllDates找到任何日期?

Kam*_*ski 7

您可以使用 Intersect

var anyOfthem = oAllDates.Intersect(MyDates).Any();
Run Code Online (Sandbox Code Playgroud)

  • @ Tommo1977请注意,`DateTime`的默认比较器也将考虑"time"部分. (2认同)