Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression for traversing through an array

i'm a lambda noob

i am looking for a way using anonymous methods to sum up the result of a count variable in my items

class SomeObject
{
    public int Count{get;}
}

SomeObject [] items = new SomeObject[]{......};  

i am looking for a lambda expression to sum up and return the Amount of all the Counts something along the lines of

Func<SomeObject[],int> counter =  // the lambada i don't know how to write.

appreciate any help and references to some good tutorials

i wan't to post another dilemma the extensions are all good an nice but what if i'm required to perform a process which is not built in for the collection like Sum , Where , Select ...ext.

for example :

     string description = string.empty; 
     foreach(var provider in Providers)
     {
            description += provider.Description ;
     }
     return decapitation .

iv'e encapsulated it in a Func delegate but i'm required to reference that delegate toan anonymous method using lambda expression which preforms the code above , i just can't figure out the syntax for doing so .

in general i am looking for a way to write a foreach loop with it's logic inside using a lambda expression

(fyi the code is exemplary and as no real use).

like image 823
eran otzap Avatar asked Jan 29 '26 07:01

eran otzap


1 Answers

You are looking for something like this:

var sum = items.Sum(i => i.Count);

Sum is an extension method provided by LINQ which sums an enumerable sequence of items. In this case, since the items (which are of type SomeObject) cannot be summed themselves, you want to use the overload of Sum that accepts a lambda. This lambda serves to extract the "summable" value from each item.

In this case, the "summable" value is the Count of each SomeObject, hence i => i.Count.

like image 142
Jon Avatar answered Jan 30 '26 21:01

Jon