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.