我遇到了一个基本问题。我需要将平面列表转换为类型为Dictionary<string,Dictionary<string,Dictionary<string,Dictionary<string,string>>>>
我几乎已经完成了,除了我需要对多个属性进行分组这一事实,并且我使用了匿名类型。这是一个例子:
List<ApprovalAction> Gen()
{
return new List<ApprovalAction>
{
new ApprovalAction { Name = "SendMailToApprover", Step="New", ApprovalRequestType = "Homeworking", ParameterName = "to", ParameterValue="Approver" },
new ApprovalAction { Name = "SendMailToApprover", Step="New", ApprovalRequestType = "Homeworking", ParameterName="subject", ParameterValue = "Aproval Request" },
new ApprovalAction { Name = "SendMailToApprover", Step="New", ApprovalRequestType = "Homeworking", ParameterName="body", ParameterValue = "I would like an approval request"},
new ApprovalAction { Name = "SendMailToApprover", Step="New", ApprovalRequestType = "Absence", ParameterName="to" , ParameterValue="Approver" },
new ApprovalAction { Name = "SendMailToApprover", Step="New", ApprovalRequestType = "Absence", ParameterName="subject", ParameterValue = "Aproval Request" },
new ApprovalAction { Name = "SendMailToApprover", Step="New", ApprovalRequestType = "Absence", ParameterName="body", ParameterValue = "I would like an approval request"}
};
}
var actions = Gen();
var dico = actions
.GroupBy(x => x.ApprovalRequestType)
.ToDictionary(
gdc => gdc.Key,
gdc => gdc.GroupBy(a => a.Step)
.ToDictionary(dd => dd.Key, dd => dd.GroupBy(x => new { x.Name, x.Step, x.ApprovalRequestType }, (key, group) => new
{
Key = key.Name,
Result = group.ToDictionary(k => k.ParameterName, v => v.ParameterValue)
})));
这是Linqpad的输出:
您知道我可以替换哪些代码来避免IEnumerable吗?
谢谢!
答案 0 :(得分:2)
IEnumerable<>
来自最终GroupBy
。如果您知道最里面的组只包含一个项目,请使用Single()
。否则使用First()
:
var dico = actions
.GroupBy(x => x.ApprovalRequestType)
.ToDictionary(
gdc => gdc.Key,
gdc => gdc.GroupBy(a => a.Step)
.ToDictionary(dd => dd.Key, dd => dd.GroupBy(x => new { x.Name, x.Step, x.ApprovalRequestType }, (key, group) => new {
Key = key.Name,
Result = group.ToDictionary(k => k.ParameterName, v => v.ParameterValue)
}).First()
)
);
上面的查询结果如下所示: