-2

How do I get the total hours worked for the following list of employees?

Live demo

using System;
using System.Collections.Generic;
    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World!");
        List<Employee> list = new();
        list.Add(new Employee{EmployeeName = "Test1", HoursWorked = "2:30"});
        list.Add(new Employee{EmployeeName = "Test1", HoursWorked = "3:30"});
    }
}
    
public class Employee
{
    public string EmployeeName { get; set; }
    
    public string HoursWorked { get; set; }
}
wohlstad
  • 12,661
  • 10
  • 26
  • 39
Rod
  • 14,529
  • 31
  • 118
  • 230
  • Does this answer your question? [How to convert HH:MM:SS string to datetime?](https://stackoverflow.com/questions/16525493/how-to-convert-hhmmss-string-to-datetime) – gunr2171 Oct 30 '22 at 03:20
  • 4
    Why would `HoursWorked` be a `string` in the first place? Do you have control over that? If so, change it. Either make it a number or else use `TimeSpan`. – jmcilhinney Oct 30 '22 at 03:26

1 Answers1

4

You can use TimeSpan.Parse to convert your HoursWorked string into a TimeSpan and accumulate it for all employees.

Then you can use the TimeSpan.TotalHours property to get the final value you need.

Complete Example:

using System;
using System.Collections.Generic;

public class Employee
{ 
    public string EmployeeName { get; set; }
    public string HoursWorked { get; set; }
}

public class Program
{
    public static double TotalEmployeeHours(List<Employee> employees)
    {
        TimeSpan totalTime = new TimeSpan();
        foreach (var emp in employees)
        {
            totalTime += TimeSpan.Parse(emp.HoursWorked);
        }
        return totalTime.TotalHours;
    }

    public static void Main()
    {
        List<Employee> list = new List<Employee>();
        list.Add(new Employee { EmployeeName = "Test1", HoursWorked = "2:30" });
        list.Add(new Employee { EmployeeName = "Test1", HoursWorked = "3:30" });

        Console.WriteLine(TotalEmployeeHours(list));
    }
}

Output:

6

Note:
TimeSpan.Parse can fail and throw an exception if the string is not in the right format. In your real code you should handle this case properly. Alternatively you can use TimeSpan.TryParse which returns a bool upon failure.

wohlstad
  • 12,661
  • 10
  • 26
  • 39