0

How to use Sum in dynamic linq query.

I have the following datasource :

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

I want to get summation of ExcuseDuration for specific emp_num in the same month of the year.


something like

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

Now I want to get the sum of ExcuseDuration?

5
  • please use Database.SqlQuery Commented May 4, 2019 at 12:10
  • 1
    Are you using Entity Framework or really just a local list? Do you really need to use dynamic Linq or will standard Linq be OK? Commented May 4, 2019 at 12:33
  • @DavidG: I have two applications,the first one should allow the user(Admin) to build rules and I want the rules to be saved in the database so I used dynamic queries so that the other applications who use these rules can use the rules directly and dynamically. Commented May 4, 2019 at 12:37
  • That answers neither of my questions, but it really looks like your question is becoming too broad to be answered here. Commented May 4, 2019 at 12:42
  • @DavidG Are you using Entity Framework or really just a local list? the list will be passed to my function so it's a local list Commented May 4, 2019 at 12:48

1 Answer 1

1

Something like:

long result = (long) li.AsQueryable().Where("EmpNum = @0", 3333).Select("it.ExcuseDuration.Ticks").Sum();
var totalDuration = new TimeSpan(result);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.