如何使用LINQ知道周期集合中是否有任何重叠 [英] How to know whether there is any overlap in a collection of periods using LINQ
问题描述
我有一个期间[FromDate, ToDate]
的集合.
我想知道给定期间与集合中各个期间之间是否存在重叠.
I would know whether there is any overlap between a given period and the periods in the collection.
我已经开始这样做了:
// periodToCheck is the given item
bool conflict = Periods.Any(p => ((p.FromDate >= periodToCheck.fromDate &&
p.FromDate <= periodToCheck.toDate)
||
(p.ToDate >= periodToCheck.fromDate &&
p.ToDate <= periodToCheck.toDate))
);
它不能涵盖所有情况的问题,例如:
The problem that it does not cover all the situation, for example:
[2010.1.1], [2010.1.31]
[2010.1.5], [2010.1.6] // Is valid in the query in spite of it is not valid
// (because there is intersection).
如果我讨论更多情况,我认为查询将变得更加复杂.
And if I discuss more situation I think the query will become more complicated.
我想知道您能否以最简单的有效方法帮助我.
I wonder if you could help me with the simplest valid way.
致谢.
推荐答案
以这种方式进行处理:如果检查日期的日期为<起始日期,或检查日期的起始日期>截止日期.这是假设check.from< = check.to.
Approach it this way instead: There is no intersaction if the check date's todate < the from date, or the check date's fromdate > the to date. This is assuming check.from <= check.to.
Periods.Any(p => !(check.ToDate < p.FromDate || check.FromDate > p.ToDate));
或(解开负片后):
Periods.Any(p => check.ToDate >= p.FromDate && check.FromDate <= p.ToDate));
这篇关于如何使用LINQ知道周期集合中是否有任何重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!