-4

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;
        }
    }
}
1
  • 1
    foreach (var l in journal.SelectMany(j => j.trans).SelectMany(t => t.line)) { .. } ? Commented Jul 5, 2019 at 5:57

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

10 Comments

A couple of questions (disclaimer: I may be wrong since it's pre-morning coffee); Doesn't this just sum up the number of positives and negatives, not the values? Also, if my caffeine is not dangerously low it enumerates the enumerable twice, so if journal is not possible to enumerate more than once, it'll break.
@JoachimIsaksson, Good morning ;) For first question, Yes I updated answer now it will sum up all values instead of positive, negatives. for second question, can you please elaborate I did not understand what you want convey here. As journal used in foreach loop it should be enumerate right? if journal is not possible to enumerate more than once, it'll break. please elaborate
jetbrains.com/help/resharper/2019.1/… has a pretty good explanation. Let's for example say that journal is an enumerable that reads the data from the database. If so, calculating posVal and negVal will ask the database once each, possibly with different results if the database is updated inbetween. It may be quite ok if journal is for example a list, but in this case we don't really know for sure :)
@JoachimIsaksson, thanks for this article, I understood and updated my answer. Now I am forcing enumeration while initializing allLines variable, in this way it will not give two different results if journal updates in between posVal and negVal.
I was not aware of this, thanks for helping me here, Have a nice day
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.