Linq-To-Entities group by

Posted by Oskar Kjellin on Stack Overflow See other posts from Stack Overflow or by Oskar Kjellin
Published on 2010-03-26T10:47:13Z Indexed on 2010/03/26 11:13 UTC
Read the original article Hit count: 502

Filed under:
|
|

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;
            }
        }

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ