0

I have a List with Objects that looks like this:

ID | ProjectID | ProjectTime | more....

And I'm trying to get a Distinct list of ProjectID with the Sum of ProjectTime.

The problem is the ProjectTime is a String in this format HH:mm ex: 06:30.

With LINQ I can group the List with GroupBy but the Sum function of LINQ doesn't accept String.

I can't change the Type of ProjectTime!

var overviewList = tmpList.GroupBy(x => x.ProjectID)
                .Select(x => new 
                {
                    ProjectID = x.Key,
                    ProjectTime = x.Sum(o => int.Parse(o.ProjectTime)) //Wrong
                });
Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
Bennobear
  • 15
  • 1
  • How would you like the output to be? I think it would be most useful as projectid/timespan like xdtTransform's answer – Caius Jard Sep 26 '19 at 07:01

3 Answers3

0

Try:

 var overviewList = tmpList
   .Select(i => new { ProjectId = i.ProjectId, 
                      Ts = TimeSpan.Parse(i.ProjectTime) })
  .GroupBy(i => i.ProjectId)
  .Select(g => new { ProjectId = g.Key,
                     Hour = g.Sum(i => i.Ts) })
  .ToList();
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

Assuming u need the string as ProjectTime, this could help you:

var overviewList = tmpList.GroupBy(x => x.ProjectID)
    .Select(x => new 
    {
        ProjectID = x.Key,
        ProjectTime = x.Sum(o => TimeSpan.Parse(o.ProjectTime).TotalMinutes)).ToString()
    });
Michael Sander
  • 2,677
  • 23
  • 29
0

Here you have to use the combinaison of 2 things:

  1. Convert the string into an usable format, that's TimeSpan
    using How to Convert string “07:35” (HH:MM) to TimeSpan

  2. The Sum the TimeSpan using Sum of TimeSpans in C#

public class Toto
{
    public int ProjectID { get; set; }
    public string ProjectTime { get; set; }
}
static void Main(string[] args)
{
    var tmpList = new[]{
        new Toto{ProjectID=1,  ProjectTime="00:10" },
        new Toto{ProjectID=2,  ProjectTime="23:20" },
        new Toto{ProjectID=2,  ProjectTime="23:30" },
        new Toto{ProjectID=1,  ProjectTime="00:40" },
    };

var overviewList = tmpList.GroupBy(x => x.ProjectID)
            .Select(x => new
            {
                ProjectID = x.Key,
                ProjectTime = new TimeSpan(x.Sum(o => TimeSpan.Parse(o.ProjectTime).Ticks))
            });

Result:

ProjectID =1, ProjectTime=00:50:00
ProjectID =2, ProjectTime=1.22:50:00

That 1.22:50:00 May not be the format you expected. But Timespan Custom format won't be usefull here.

If you need to get the same string format again. You can use, but keep the format TimeSpan as long as you use it use that only for display.

 (int)X.ProjectTime.TotalHours +":" +X.ProjectTime.Minutes

ProjectID =1, ProjectTime=0:50
ProjectID =2, ProjectTime=46:50

xdtTransform
  • 1,986
  • 14
  • 34