我试图重构一些嵌套的foreach
循环,但遇到了一个问题。这是原始代码:
foreach(var doc in customTrackerDocuments)
{
foreach(var rule in doc.Rules)
{
foreach(var eval in rule.Evaluations)
{
// Do something with customTrackerDocuments, rules, and evaluations
// doc, rule, and eval are all available here
}
}
}
这无疑是干净利落的,所以也许应该保持这样。但是,我一直试图降低复杂性并提高可读性,所以我尝试了这个:
foreach(var eval in customTrackerDocuments.SelectMany(doc => doc.Rules).SelectMany(rule => rule.Evaluations))
{
// Do something with customTrackerDocuments, rules, and evaluations
// doc and rule are NOT available here
}
问题是文档和规则不再可用于循环中。有没有办法让这些方法可用?或者我应该只使用具有三个嵌套循环的第一个选项?
我有一个小提琴:https://dotnetfiddle.net/oBMfQC
答案 0 :(得分:3)
它们不可用,因为您只在最终的rule.Evaluations
投射SelectMany
。你可以建立一个匿名类型:
foreach(var eval in customTrackerDocuments.SelectMany(doc => doc.Rules, rule => new {doc, rule})
.SelectMany(docrule => docrule.rule.Evaluations, eval => new {docrule.doc, docrule.rule, eval}))
{
// eval.doc, eval,rule, eval.eval are available here
}
是否更具可读性或更简单性是值得商榷的。它肯定不会更快或使用更少的内存。