1

I have a struct like this:

public struct Response
{
    public string Cmd;
}

And also in main I'm having this byte array:

Decode(StringToByteArray("0100002402433131000000000000000311"));

And then I have a decode function inside this function I want to do Take(5) and Skip (3) like this:

byte[] cmd = resp.Skip(5).Take(3).ToArray();
x.Cmd = Encoding.UTF8.GetString(cmd);

How can i make this Modular as i need to the same to many function that might be the position is different is there anyway that instead of using Take(3) or Skip (5) i can assign Variable to calculate this automatically?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 2
    Create a function for that? – zerkms Dec 19 '12 at 04:06
  • 1
    And pass 5 and 3 as argument to that function? – Alexei Levenkov Dec 19 '12 at 04:08
  • How?! i should't touch the Modularity of my existing function as my Communication will follow my standard however i need to replace Take(3) with Something that like Take(bcmd.Length ) so far im having Error on that because of the different data type – Alexandera MacQueen Dec 19 '12 at 04:09
  • This 5 and 3 position will be different in another Decode strings i need something more smart to calculate and estimate the position base of Cmd Size – Alexandera MacQueen Dec 19 '12 at 04:10
  • @Artinos: "i should't touch the Modularity of my existing function as my Communication will follow my standard " -- I can't begin to fathom what this means. – siride Dec 19 '12 at 04:37

2 Answers2

2

Here's your other function:

public T[] SkipTake<T>(IEnumerable<T> items, int skipCount, int takeCount) {
    return items.Skip(skipCount).Take(takeCount).ToArray();
}

It uses generics, so I'd read up on those (http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.90).aspx).

siride
  • 200,666
  • 4
  • 41
  • 62
1

Personally ild make it an extention method, (same idea as @siride but a bit more fluent)

eg

public static class SkipTakeExtentions{
    public static T[] SkipTake<T>(this IEnumerable<T> items, int skipCount, int takeCount) {
        return items.Skip(skipCount).Take(takeCount).ToArray();
    }
}

usage:

thing.SkipTake(1,2);
undefined
  • 33,537
  • 22
  • 129
  • 198