如何使用动态查询获取特定属性的总和

时间:2019-05-04 12:05:36

标签: c# linq aggregate dynamic-linq

如何在动态linq查询中使用Sum。

我有以下数据源:

List<Excuse> li = new List<Excuse>();
li.Add(new Excuse { EmpNum = 3333, ExcuseDate = DateTime.Today, ExcuseDuration = new TimeSpan(0, 30, 0), ExcuseType = 0, Id = 1 });
li.Add(new Excuse { EmpNum = 3333, ExcuseDate = DateTime.Today.AddDays(1), ExcuseDuration = new TimeSpan(2, 30, 0), ExcuseType = 0, Id = 2 });
li.Add(new Excuse { EmpNum = 3333, ExcuseDate = DateTime.Today.AddDays(2), ExcuseDuration = new TimeSpan(2, 0, 0), ExcuseType = 0, Id = 3 });
li.Add(new Excuse { EmpNum = 2345, ExcuseDate = DateTime.Now, ExcuseDuration = new TimeSpan(0, 30, 0), ExcuseType = 0, Id = 4});

  

我想获取特定ExcuseDurationemp_num的总和   一年中的同一个月。


类似

var langExp2 = "YEAR(ExcuseDate) = @1 AND MONTH(ExcuseDate) = @2 AND emp_num = @3";
var query1 = li.AsQueryable().Where(langExp2, 2019,5,3333)

现在我想得到ExcuseDuration的总和吗?

1 个答案:

答案 0 :(得分:1)

类似的东西:

long result = (long) li.AsQueryable().Where("EmpNum = @0", 3333).Select("it.ExcuseDuration.Ticks").Sum();
var totalDuration = new TimeSpan(result);