如何将此sql部分转换为linq

时间:2016-04-15 12:03:40

标签: sql linq sql-to-linq-conversion

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

我想要的是将语句转换为linq select语句

1 个答案:

答案 0 :(得分:2)

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

如果你想知道差异而不必担心负值,那么将计算包装在Math.Abs​​中

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

在此示例中,您的结果为7