Moving elements in array c#

后端 未结 4 1502
感情败类
感情败类 2021-01-12 07:59

I have this very simple array which I want to be able to move around some items in. Are there any built in tools in c# to do this? If not, du you have any suggestion in how

4条回答
  •  臣服心动
    2021-01-12 08:31

    EDIT: Okay, now you've changed the example, there's nothing built-in - and it would actually be a bit of a pain to write... you'd need to consider cases where you're moving it "up" and where you're moving it "down", for example. You'd want unit tests, but I think this should do it...

    public void ShiftElement(this T[] array, int oldIndex, int newIndex)
    {
        // TODO: Argument validation
        if (oldIndex == newIndex)
        {
            return; // No-op
        }
        T tmp = array[oldIndex];
        if (newIndex < oldIndex) 
        {
            // Need to move part of the array "up" to make room
            Array.Copy(array, newIndex, array, newIndex + 1, oldIndex - newIndex);
        }
        else
        {
            // Need to move part of the array "down" to fill the gap
            Array.Copy(array, oldIndex + 1, array, oldIndex, newIndex - oldIndex);
        }
        array[newIndex] = tmp;
    }
    

    You should probably consider using a List instead of an array, which allows you to insert and remove at particular indexes. Those two operations will be more expensive than only copying the relevant section, but it'll be a lot more readable.

提交回复
热议问题