ArraySegment - Returning the actual segment C#

前端 未结 4 547
野性不改
野性不改 2020-12-10 02:50

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

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 03:41

    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();
    

提交回复
热议问题