12,548,876 members (51,328 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
 Suvendu Shekhar Giri 115 Dave Kreskowiak 100 ppolymorphe 100 OriginalGriff 95 Rbabs 75
 OriginalGriff 3,892 Suvendu Shekhar Giri 1,713 John Simmons / outlaw programmer 1,687 ppolymorphe 1,541 Karthik Bangalore 1,210