我正在构建一个用于时间报告的软件
我有一台Dictionary<string, Dictionary<string, double>>。主字典中的关键字是用户名,它们的值是的字典。
我有一个函数GetDepartment(string UserName),它返回一个包含用户部门的字符串。
我想要的是创建一个相同类型的新字典,它将部门作为主键,并且在子字典a中,其中小时是该部门的总和。
我一直在尝试用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;
}
}发布于 2010-03-26 19:33:27
为什么你想用LINQ来做这个?我不认为它会更清晰,加上LINQ查询不太容易调试。
下面的表达式在LINQ to Entities中不起作用,因为您不能在LINQ to Entities中调用GetDepartment等C#函数。
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。至少它应该给你一个关于如何做到这一点的想法。
发布于 2010-03-26 21:45:44
这是我对它的看法。
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
);https://stackoverflow.com/questions/2522594
复制相似问题