我有一个查询,其中我想检查两行指向同一时间或重叠时间跨度的位置 e.g
object1.startDate=07/12/2015
object1.endDate=12/12/2015
object2.startDate=08/12/2015
object2.endDate=08/12/2015
我们如何比较linq查询中的object1
和object2
的持续时间,以检查两个对象在何处具有相同/重叠的时间段
答案 0 :(得分:1)
您可以通过以下逻辑执行此操作:
if(object1.endDate >= object2.startDate && object1.startDate <= object2.endDate)
{
//overlaping logic here
}
用法示例:
public class test
{
public int id;
public DateTime st;
public DateTime et;
}
class Program
{
static void Main(string[] args)
{
var list = new List<test>()
{
new test{id = 1, st = DateTime.Parse("2015-10-15"), et = DateTime.Parse("2015-10-18")},
new test{id = 2, st = DateTime.Parse("2015-10-16"), et = DateTime.Parse("2015-10-17")},
new test{id = 3, st = DateTime.Parse("2015-10-17"), et = DateTime.Parse("2015-10-17")},
new test{id = 4, st = DateTime.Parse("2015-10-25"), et = DateTime.Parse("2015-10-26")},
};
var result = (from l1 in list
from l2 in list
where l1.id > l2.id && l1.et >= l2.st && l1.st <= l2.et
select new { l1= l1.id, l2 = l2.id}).ToList();
}
}
输出:
+ [0] { l1 = 2, l2 = 1 } <Anonymous Type>
+ [1] { l1 = 3, l2 = 1 } <Anonymous Type>
+ [2] { l1 = 3, l2 = 2 } <Anonymous Type>