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

后端 未结 4 673
说谎
说谎 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:51

    If FromDate <= ToDate always holds true for your Period objects, you can define a helper extension method OverlapsWith as follows:

    public static bool OverlapsWith(this Period a, Period b)
    {
        return !(b.ToDate <= a.FromDate || a.ToDate <= b.FromDate);
    }
    

    To illustrate what's going on, let's look at the two cases where there is no overlap between a and b:

    //                         a
    //                |-----------------|
    //   |--------|                          |-----------|
    //       b1                                    b2
    

    You can check the above condition against this diagram. Since the diagram shows the cases where no overlap occurs, but the method really ought to test for overlap, the condition needs to be negated. It could be simplified to the following:

               b.ToDate > a.FromDate && a.ToDate > b.FromDate
    

    When you use this method in a LINQ query, it turns out very easy to understand:

        Periods.Any(period => period.OverlapsWith(periodToCheck))
    

提交回复
热议问题