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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With