Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,

I have written this function which is as follows:

C#
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?

Many thanks in advance.
Posted
Updated 20-Jun-12 3:54am
v3

1 solution

C#
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:
C#
data.Select((value, index) => new KeyValuePair<int, byte>(index, value)).Sum(k => (k.Value & 0xff) << (8 * k.Key));
 
Share this answer
 
v3
Comments
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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900