akash akash - 7 months ago 32
SQL Question

How to convert this sql part to linq

select sum(DATEDIFF(day,LeaveBreakup.StartDate,LeaveBreakup.EndDate)+1)


what I want is to convert the statement to linq select statement

Answer
class LeaveBreakup
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

List<LeaveBreakup> Dates = new List<LeaveBreakup>();
Dates.Add(new LeaveBreakup(){StartDate = DateTime.Now.AddDays(-3), EndDate = DateTime.Now });
Dates.Add(new LeaveBreakup(){StartDate = DateTime.Now.AddDays(-2), EndDate = DateTime.Now });

LINQ BIT

var Result = (from D in Dates
                select (D.EndDate - D.StartDate).TotalDays + 1)
            .Sum();

If you want to know the diff without having to worry about having a negative value then wrap the calculation in Math.Abs

var Result = (from D in Dates
                select Math.Abs((D.StartDate - D.EndDate).TotalDays) + 1)
            .Sum();

In this example your Result is 7