-3

How can I write foreach loop shown below as a labmda expression?

var sum = 0;
foreach (SomeClass obj in SomeListOfClass)
{
   sum += obj.SomeValue;
}

I am expecting a lambda expression that look like this

var sum = SomeListOfClass.ForEachMethod( x => sum += x.SomeValue)

Is there any way to do it?

Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
talaa123
  • 123
  • 1
  • 2
  • 14
  • 3
    You could just use Linq's `Sum` extension method `var sum = SomeListOfClass.Sum(x => x.SomeValue);` – juharr Mar 09 '16 at 18:06
  • This may help you: [http://stackoverflow.com/questions/858978/lambda-expression-using-foreach-clause](http://stackoverflow.com/questions/858978/lambda-expression-using-foreach-clause) – Dimitar Popov Mar 09 '16 at 18:11
  • Why so many downvotes? What's exactly wrong with the question. Didn't understand? – talaa123 Mar 09 '16 at 20:42
  • @talaa123 Well, your code doesn't make much sense (why are you adding to `sum` in the lambda and also setting it to the return value?) and you apparently didn't look at the documentation, where you would find `Sum()` and `ForEach()`. You also didn't explain why do you want to use a lambda. – svick Mar 12 '16 at 22:13

2 Answers2

3

Use Linq:

using System.Linq;

var sum = list.Sum(x => x.SomeValue);
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
2

For the special case at hand (sum), you can use Linq's Sum method.

SomeListOfClass.Sum(c => c.Property);

This however, is just a special case of Aggregate. If you need more complicate aggregation of your list, you'd use that.
Here is an example that sums up the values of integers:

var ints = new List<int>() { 1, 2, 3 };
var x = ints.Aggregate((start, current) => start + current);
Domysee
  • 12,718
  • 10
  • 53
  • 84