小编典典

删除常规数组的元素

c#

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

我需要类似于RemoveAt()常规数组的东西。


阅读 271

收藏
2020-05-19

共1个答案

小编典典

如果您不想使用列表:

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

您可以尝试我尚未实际测试过的这种扩展方法:

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);
2020-05-19