C# Linq到对象分组方式

C# Linq到对象分组方式,c#,linq,group-by,C#,Linq,Group By,我正在开发一个时间报告软件 我有一本字典。主字典中的键是用户名,其值是的字典 我有一个函数GetDepartmentstring UserName,它返回一个带有用户部门的字符串 我想要的是装箱一本新字典,类型相同,以部门为主键,在子字典a中,小时数是该部门的总数 我一直在尝试与linq合作,但没有成功。我很高兴能在这里得到帮助 编辑:这段代码正是我想要的。但我想把它放在林肯 Dictionary<string, Dictionary<string, double&g

我正在开发一个时间报告软件


我有一本字典。主字典中的键是用户名,其值是的字典

我有一个函数GetDepartmentstring UserName,它返回一个带有用户部门的字符串

我想要的是装箱一本新字典,类型相同,以部门为主键,在子字典a中,小时数是该部门的总数

我一直在尝试与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;
            }
        }

你为什么要对LINQ这么做?我不认为这会更清楚,而且LINQ查询也不容易调试

以下表达式在LINQtoEntities中不起作用,因为您不能在那里调用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);
我不确定这是否没有bug。至少它应该给你一个如何做到这一点的想法。

以下是我对它的看法

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

它们的价值是……的字典。。。什么?你确定你是按照你的标题建议使用LINQ到实体,而不是LINQ到对象吗?@jens纠正了我的标题错误@马塞洛:这是一对键值对。键值对有一个键和一个值