Linq-To-Objects组由

时间:2010-03-26 10:47:14

标签: c# linq group-by

我正在构建一个用于时间报告的软件

我有Dictionary<string, Dictionary<string, double>>。主词典中的键是用户名,其值是字典。

我有一个函数Ge​​tDepartment(string UserName),它返回一个包含用户部门的字符串。

我想要的是创建一个相同类型的新字典,其中部门作为主键,而在子字典中则表示小时是该部门的总数。

我一直试图用linq做这个但是没有成功。很高兴在这里得到一些帮助!

编辑:此代码完全符合我的要求。但我想在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;
            }
        }

2 个答案:

答案 0 :(得分:2)

为什么要使用LINQ执行此操作?我不认为它会更清楚,加上LINQ查询不是那么容易调试。

以下表达式在LINQ to Entities中不起作用,因为你不能在那里调用C#函数,比如GetDepartment。

Dictionary<string, Dictionary<string, double>> temphours 
    = (from user in hours
       group user by GetDepartment(user.Key) into department
       select new {
          Key = department.Key
          Value = (from userInDepartment in department
                   from report in userInDepartment.Value
                   group report by report.Key into g // To tired to think of a name =)
                   select new {
                       Key = g.Key
                       Value = g.Sum(reportInG => reportInG.Value)
                   }).ToDictonary(ud => ud.Key, ud=> ud.Value);
       }).ToDictonary(u => u.Key, u=> u.Value);

我不确定这是没有错误的。至少它应该让你知道如何做到这一点。

答案 1 :(得分:1)

这是我的看法。

Dictionary<string, Dictionary<string, double>> temphours =
(
  from user in hours
  let department = GetDepartment(user.Key)
  from customerReport in user.Value
  group customerReport by department
)
.ToDictionary(
  g => g.Key,
  g => g.GroupBy(rep => rep.Key).ToDictionary
  (
    g2 => g2.Key,
    g2 => g2.Sum(rep => rep.Value)
  )
);

这是直接的,因为我可以做到。如果你想要更具描述性,那么这可能会为你做到:

Dictionary<string, Dictionary<string, double>> temphours =
(
  from user in hours
  let department = GetDepartment(user.Key)
  from customerReport in user.Value
  group customerReport by department into reportGroup
  select new
  {
    Department = reportGroup.Key,
    Reports =
    (
       from report in reportGroup
       group report.Value by report.Key
    ).ToDictionary(g => g.Key, g => g.Sum())
  }
)
.ToDictionary{
  x => x.Department,
  x => x.Reports
);