Muhammad Nasir
Muhammad Nasir

Reputation: 2204

How to compare duration of two DateTime objects in linq

I have a query in which i want to check where two two rows pointing to same time or overlapping time time span e.g

object1.startDate=07/12/2015
object1.endDate=12/12/2015

object2.startDate=08/12/2015
object2.endDate=08/12/2015

how can we compare duration of object1 and object2 in linq query to check where the two object have same/overlapping time period

Upvotes: 0

Views: 44

Answers (1)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35790

You can do this by the following logic:

if(object1.endDate >= object2.startDate && object1.startDate <= object2.endDate)
{
    //overlaping logic here
}

Usage example:

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();
    }
}

Output:

+       [0] { l1 = 2, l2 = 1 }  <Anonymous Type>
+       [1] { l1 = 3, l2 = 1 }  <Anonymous Type>
+       [2] { l1 = 3, l2 = 2 }  <Anonymous Type>

Upvotes: 1

Related Questions