删除规则阵列的元件阵列、元件、规则

2023-09-02 01:18:44 作者:兜兜冇餹

我的Foo对象的数组。如何删除数组的第二个元素?

I have an array of Foo objects. How do I remove the second element of the array?

我需要类似的东西 RemoveAt()但对于一个普通的数组。

I need something similar to RemoveAt() but for a regular array.

推荐答案

如果您不希望使用清单:

If you don't want to use List:

var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();

您可以试试这个扩展方法,我没有实际测试过:

You could try this extension method that I haven't actually tested:

public static T[] RemoveAt<T>(this T[] source, int index)
{
    T[] dest = new T[source.Length - 1];
    if( index > 0 )
        Array.Copy(source, 0, dest, 0, index);

    if( index < source.Length - 1 )
        Array.Copy(source, index + 1, dest, index, source.Length - index - 1);

    return dest;
}

和使用它像:

Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);