13,089,818 members (49,258 online)
Rate this:
See more:
Hello All,

I have written this function which is as follows:

```public static long ByteArrayToLong(byte[] input)
{
long accumulator=0;
byte counter = 0;

for (counter=0; counter<input.Length -1; counter++)
accumulator += (input[counter] & 0xff) << (8 * counter);

return accumulator;

}```

Could anybody tell me how I can do this in lambda please?

Posted 29-Mar-12 6:02am
Updated 20-Jun-12 3:54am
v3

Rate this:

## Solution 1

```Func<byte[], long> f = (input) =>
{
long accumulator=0;
byte counter = 0;

for (counter=0; counter<input.Length -1; counter++)
accumulator += (input[counter] & 0xff) << (8 * counter);

return accumulator;
}
long result = f(new byte[] {0,4,1});```

Or:
`data.Select((value, index) => new KeyValuePair<int, byte>(index, value)).Sum(k => (k.Value & 0xff) << (8 * k.Key));`
v3
Henning Dieterichs 29-Mar-12 12:19pm

See my update. Not very nice (as it is not really sense-full), but should work.
Henning Dieterichs 29-Mar-12 18:35pm

Maybe I am the best (yes, pride goes before a fall :) ), but my second solution is not...
This lambda expression is bad, as the intermediate step with "select" is an ugly hack (better: write your own sum-extension-method method which passes both index and value).

Lambda in C# is nothing more than "=>" which represents an anonymous function.
So my first solution is already a complete lambda expression.

What you wanted, is using the default LINQ (language integrated query) in connection with lambda, which is realized through extension-methods on IEnumerable<t>. For LINQ you have not to use lambda-expressions and for lambda-expressions you dont have to use LINQ.
As the most LINQ-extension-methods on IEnumerable<t> returns again IEnumerable<t> and take a Predicate (= Func<T, Boolean> = delegate boolean (T element)) you can do some cool stuff.

If you want to learn lambda-expressions and LINQ, you should play around with them: define an array (e.g. int[]) and look what methods Intelli-Sense suggest you.

Greetings,
Henning

Top Experts
Last 24hrsThis month
 ProgramFOX 270 Richard Deeming 220 OriginalGriff 140 ppolymorphe 120 Jochen Arndt 115
 OriginalGriff 3,402 Graeme_Grant 1,784 ProgramFOX 1,707 Jochen Arndt 1,645 ppolymorphe 1,487