Select a section of a byte array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Airslash
    New Member
    • Nov 2007
    • 221

    Select a section of a byte array

    Hello,

    I'm currently working with byte arrays to hold data transmitted over the network, and i'm looking for a way to copy a section of that byte array and return it from a function result.

    I know I can create a temporary array and call the CopyTo function to copy the data in that array, but I was wondering this this piece of code below with LinQ would do the same.

    Code:
    return (from m in Enumerable.Range(0, Size) select RawContent[64 + m]);
    - RawContent is a property that returns a byte[] array
    - Size is a long that gives the range of the data to copy
    - 64 is the offset in Rawcontent to copy from.

    Would this call return a byte array with the values from RawContent[64]-> RawContent[Size] ?


    EDIT: changed the range setting.
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    Not, this won't return an array, this will return an IEnumerable<byt e>. You have to call .ToArray() to get back a byte[].

    Secondly this won't return index 64 to Size but 64 to 64+Size.


    You can define an offset in Enumerable.Rang e like Enumerable.Rang e(64, Size), so you don't have to write m+64.

    Code:
      return (from offset in Enumerable.Range(64, Size)
              //where offset <= RawContent.GetUpperBound(0) //if you want to, uncomment this line to avoid IndexOutOfBounds
              select RawContent[offset]).ToArray();

    Comment

    • Airslash
      New Member
      • Nov 2007
      • 221

      #3
      Originally posted by ChBinder
      Not, this won't return an array, this will return an IEnumerable<byt e>. You have to call .ToArray() to get back a byte[].

      Secondly this won't return index 64 to Size but 64 to 64+Size.


      You can define an offset in Enumerable.Rang e like Enumerable.Rang e(64, Size), so you don't have to write m+64.

      Code:
        return (from offset in Enumerable.Range(64, Size)
                //where offset <= RawContent.GetUpperBound(0) //if you want to, uncomment this line to avoid IndexOutOfBounds
                select RawContent[offset]).ToArray();
      thanks for the clarification.
      I've currently worked around the issue by passing the same data array to the read function as a reference and add an additional parameter so it either overwriters the data or appends to it depending on the settings.

      Thanks for the pointer on the size & offset. Added some checks to validate the size of the array....slippe d my mind.

      Comment

      Working...