How to know whether there is any overlap in a collection of periods using LINQ

后端 未结 4 670
说谎
说谎 2021-01-05 23:08

I have a collection of periods [FromDate, ToDate].

I would know whether there is any overlap between a given period and the periods in the collection.

4条回答
  •  孤独总比滥情好
    2021-01-05 23:48

    Do 2 periods having common date, say ToDate for period 1 and FromDate of period 2 are the same, count as in intersection ?

    If yes then a little modification to your query to simply check the dates of a period if are within the checked period separately as if one of the dates falls inside a period then there is intersection:

    bool conflict = Periods.Any(p => ((p.FromDate >= periodToCheck.fromDate && 
                                        p.ToDate <= periodToCheck.fromDate)
                                      ||
                                       (p.FromDate >= periodToCheck.toDate && 
                                        p.ToDate <= periodToCheck.toDate))
                                 );
    

提交回复
热议问题