Linq单个集合中的重叠日期范围检查 [英] Linq Overlapped date range checking in single collection

查看:60
本文介绍了Linq单个集合中的重叠日期范围检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class TimeRange{
  private DateTime StartDate{get; set;}
  private DateTime EndDate{get; set;}
}

List<TimeRange> TimeRangeList = new List<TimeRange>(){
  new TimeRange(){StartDate = new DateTime(2050, 1, 1), 
                    EndDate = new DateTime(2050, 1, 10)},
  new TimeRange(){StartDate = new DateTime(2050, 2, 1), 
                    EndDate = new DateTime(2050, 2, 10)},
  //This item will triggered the overlap validation failed
  new TimeRange(){StartDate = new DateTime(2050, 1, 5),
                    EndDate = new DateTime(2050, 1, 9)},
                              },
}

所以在我查看了类似主题后,我仍然可以't找出了检查重叠日期范围的算法.

so after I checked out the similar topic, I still can't figured out the algorithm of checking the overlapped date range.

根据检查多个日期范围对象之间的日期重叠

我只需要比较两个日期范围

I just need to compare two date range like this

SELECT COUNT(*)
FROM Table1
WHERE Table1.StartDate < 'endCheckDate'
AND Table1.EndDate > 'startCheckDate'

我发现在Linq中很难做到,我们如何比较其中一个馆藏中的所有物品?原因是我们可以像比较两个列表一样在循环中使用foreach,但是在select中如何工作?

I found it is difficult to do in Linq, how do we compare all items in one collection within? of cause we can use foreach in just loop the collection just like comparing two list, but how is it work in select?

实际上我在做这样的事情

actually I'm doing something like this

for (int i = 0; i < TimeRangeList .Count(); ++i)
{
        var item = TimeRangeList[i];                    
        for (int y = i + 1; y < TimeRangeList.Count(); ++y)
        {
                var item2 = TimeRangeList[y];

                if (IsOverLapped(item, item2))
                {
                    // this is overlapped
                };
        }
}

private bool IsOverLapped(dynamic firstObj, dynamic secondObj)
{
        return secondObj.StartDate <= firstObj.EndDate && firstObj.StartDate <= secondObj.EndDate;
}

是否有一种更优雅的方法可以不循环?

Is there a more elegant way to do without looping?

所以我的问题是,我们如何通过linq比较每个项目本身的单个列表?

so my questions is how do we compare one single list for each items itself by linq?

推荐答案

一个简单的蛮力想法:

bool overlap = TimeRangeList
    .Any(r => TimeRangeList
         .Where(q => q != r)             
         .Any(q => q.EndDate >= r.StartDate && q.StartDate <= r.EndDate) );

这篇关于Linq单个集合中的重叠日期范围检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆