How do I clone a range of array elements to a new array?

前端 未结 25 1411
北海茫月
北海茫月 2020-11-22 16:07

I have an array X of 10 elements. I would like to create a new array containing all the elements from X that begin at index 3 and ends in index 7. Sure I can easily write a

25条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 16:48

    As an alternative to copying the data you can make a wrapper that gives you access to a part of the original array as if it was a copy of the part of the array. The advantage is that you don't get another copy of the data in memory, and the drawback is a slight overhead when accessing the data.

    public class SubArray : IEnumerable {
    
       private T[] _original;
       private int _start;
    
       public SubArray(T[] original, int start, int len) {
          _original = original;
          _start = start;
          Length = len;
       }
    
       public T this[int index] {
          get {
             if (index < 0 || index >= Length) throw new IndexOutOfRangeException();
             return _original[_start + index];
          }
       }
    
       public int Length { get; private set; }
    
       public IEnumerator GetEnumerator() {
          for (int i = 0; i < Length; i++) {
            yield return _original[_start + i];
          }
       }
    
       IEnumerator IEnumerable.GetEnumerator() {
          return GetEnumerator();
       }
    
    }
    

    Usage:

    int[] original = { 1, 2, 3, 4, 5 };
    SubArray copy = new SubArray(original, 2, 2);
    
    Console.WriteLine(copy.Length); // shows: 2
    Console.WriteLine(copy[0]); // shows: 3
    foreach (int i in copy) Console.WriteLine(i); // shows 3 and 4
    

提交回复
热议问题