C# quickest way to shift array

前端 未结 20 1287
礼貌的吻别
礼貌的吻别 2020-12-01 01:35

How can I quickly shift all the items in an array one to the left, padding the end with null?

For example, [0,1,2,3,4,5,6] would become [1,2,3,4,5,6,null]

Ed

20条回答
  •  隐瞒了意图╮
    2020-12-01 02:26

    The quickest way to do this is to use Array.Copy, which in the final implementation uses a bulk memory transfer operation (similar to memcpy):

    var oldArray = new int?[] { 1, 2, 3, 4, 5, 6 };
    var newArray = new int?[oldArray.Length];
    Array.Copy(oldArray, 1, newArray, 0, oldArray.Length - 1);
    // newArray is now { 2, 3, 4, 5, 6, null }
    

    Edited: according to the documentation:

    If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten.

    So if you don't want to allocate a new array, you can pass in the original array for both source and destination--although I imagine the tradeoff will be a somewhat slower performance since the values go through a temporary holding position.

    I suppose, as in any investigation of this kind, you should do some quick benchmarking.

提交回复
热议问题