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

前端 未结 25 975
北海茫月
北海茫月 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:52

    As far as cloning goes, I don't think serialization calls your constructors. This may break class invariants if you're doing interesting things in the ctor's.

    It seems the safer bet is virtual clone methods calling copy constructors.

    protected MyDerivedClass(MyDerivedClass myClass) 
    {
      ...
    }
    
    public override MyBaseClass Clone()
    {
      return new MyDerivedClass(this);
    }
    
    0 讨论(0)
  • 2020-11-22 16:53

    There's no single method that will do what you want. You will need to make a clone method available for the class in your array. Then, if LINQ is an option:

    Foo[] newArray = oldArray.Skip(3).Take(5).Select(item => item.Clone()).ToArray();
    
    class Foo
    {
        public Foo Clone()
        {
            return (Foo)MemberwiseClone();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 16:53

    I'm not sure how deep it really is, but:

    MyArray.ToList<TSource>().GetRange(beginningIndex, endIndex).ToArray()

    It's a bit of overhead, but it might cut out an unnecessary method.

    0 讨论(0)
  • 2020-11-22 16:53
    public   static   T[]   SubArray<T>(T[] data, int index, int length)
            {
                List<T> retVal = new List<T>();
                if (data == null || data.Length == 0)
                    return retVal.ToArray();
                bool startRead = false;
                int count = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    if (i == index && !startRead)
                        startRead = true;
                    if (startRead)
                    {
    
                        retVal.Add(data[i]);
                        count++;
    
                        if (count == length)
                            break;
                    }
                }
                return retVal.ToArray();
            }
    
    0 讨论(0)
  • 2020-11-22 16:55

    I think that the code you are looking for is:

    Array.Copy(oldArray, 0, newArray, BeginIndex, EndIndex - BeginIndex)

    0 讨论(0)
  • 2020-11-22 16:56

    The following code does it in one line:

    // Source array
    string[] Source = new string[] { "A", "B", "C", "D" };
    // Extracting a slice into another array
    string[] Slice = new List<string>(Source).GetRange(2, 2).ToArray();
    
    0 讨论(0)
提交回复
热议问题