Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
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?
 
Many thanks in advance.
Posted 29-Mar-12 6:02am
Edited 20-Jun-12 3:54am
v3

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

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));
  Permalink  
v3
Comments
Henning Dieterichs at 29-Mar-12 12:19pm
   
See my update. Not very nice (as it is not really sense-full), but should work.
Henning Dieterichs at 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. 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 returns again IEnumerable and take a Predicate (= Func = 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)



Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 20 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100