Q:

Use Linq instead of nested foreach loops to sum values

I want to find the sum of values without using a nested foreach loop
How do I write this using Linq instead?
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;
        }
    }
}

A:

You can use 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);

