I have been looking around on ways to return the segment which is basically held by ArraySegment in terms of offset and count. Although ArraySegment holds the complete and o
I use the following set of extension methods to work with array segments:
#region ArraySegment related methods
public static ArraySegment GetSegment(this T[] array, int from, int count)
{
return new ArraySegment(array, from, count);
}
public static ArraySegment GetSegment(this T[] array, int from)
{
return GetSegment(array, from, array.Length - from);
}
public static ArraySegment GetSegment(this T[] array)
{
return new ArraySegment(array);
}
public static IEnumerable AsEnumerable(this ArraySegment arraySegment)
{
return arraySegment.Array.Skip(arraySegment.Offset).Take(arraySegment.Count);
}
public static T[] ToArray(this ArraySegment arraySegment)
{
T[] array = new T[arraySegment.Count];
Array.Copy(arraySegment.Array, arraySegment.Offset, array, 0, arraySegment.Count);
return array;
}
#endregion
You can use them as follows:
byte[] input = new byte[5]{1,2,3,4,5};
ArraySegment delimited = input.GetSegment(0, 2);
byte[] segment = delimited.ToArray();