Linq-To-Objects group by
- by Oskar Kjellin
Hey,
I'm building a software for timereporting
I have a Dictionary<string, Dictionary<string, double>>. The key in the main dictionary is a users name and their value is a dictionary of .
I have a function GetDepartment(string UserName) which returns a string with the users department.
What I want is to crate a new dictionary, of the same type, that has the department as the main key and in the subdictionary a where hours is the total for that department.
I have been trying to do this with linq but did not succeed. Would be very glad for some help here!
EDIT: This code does exactly what I want. But I want it in LINQ
Dictionary<string, Dictionary<string, double>> temphours = new Dictionary<string, Dictionary<string, double>>(); ;
foreach (var user in hours)
{
string department = GetDepartment(user.Key);
if (!temphours.ContainsKey(department))
{
temphours.Add(department, new Dictionary<string, double>());
}
foreach (var customerReport in user.Value)
{
if (!temphours[department].ContainsKey(customerReport.Key))
{
temphours[department].Add(customerReport.Key, 0);
}
temphours[department][customerReport.Key] += customerReport.Value;
}
}