我想在不使用嵌套的foreach循环的情况下找到值的总和
我该如何使用Linq编写此代码?
decimal posVal = 0;
decimal negVal = 0;
foreach (var j in journal)
{
foreach (var t in j.trans)
{
foreach (var l in t.line)
{
if (l.val > 0)
posVal += l.val;
else
negVal += l.val;
}
}
}
答案 0 :(得分:3)
您可以使用SelectMany,
var allLines = journal
.SelectMany(j => j.trans
.SelectMany(l => l.line)
.ToList();
var posVal = allLines.Where(x => x.val > 0).Sum(x => x.val);
var negVal = allLines.Where(x => x.val < 0).Sum(x => x.val);