0

I am querying my database which has the following

Table: TimeEntries

  • field1: ProjectName
  • field2: Phase
  • field3: TimeWorked

What I am trying to do is group by ProjectName and Phase and sum() the TimeWorked for each.

So if I had this in the table for: ProjectName, Phase, Timeworked

  1. Project1--- 1 --- 3.5
  2. Project1 --- 1 --- 2
  3. Project2 --- 1 --- 1

My query would return:

  1. Project1---1---5.5
  2. Project2---1---1

currently this is what I have:

var query3 = (from timeEntry in context.TimeEntries
   select new
      {
          ProjectName = timeEntry.ProjectName,
          Phase = timeEntry.Phase,
          LoggedHours = context.TimeEntries.Sum(x => x.TimeWorked)
      });

Not sure if I am even on the right track, could someone help me out?

Here is a picture of the database tables with their data types: TimeEntry Table, Project Table

Ryan C
  • 572
  • 5
  • 18
Eric Obermuller
  • 245
  • 3
  • 19
  • See the first answer on [LINQ GroupBy Sum and Count](https://stackoverflow.com/questions/16522645/linq-groupby-sum-and-count) and adapt to your needs – Mad Myche Feb 20 '18 at 19:42
  • This looks oddly similar to [this question](https://stackoverflow.com/questions/48892874/perform-calculations-on-a-set-using-only-linq) asked a few minutes ago. There's enough difference that I could be imagining it. But both involve adding the total time worked for a set of entries, and both specify using LINQ. – Scott Hannen Feb 20 '18 at 19:48
  • The answers here may also help with the groupby part. I see you are attempting to group by 2 fields. https://stackoverflow.com/questions/847066/group-by-multiple-columns. – Andrew Feb 20 '18 at 19:52

1 Answers1

0

Try This

    var result=context.TimeEntries.GroupBy(m=>new {m.Name,m.Phase})
.Select(m=>new {
Name=m.Key.Name,
Phase=m.Key.Phase,
TimeWorked=m.Sum(o=>o.TimeWorked)

});