我有一个 Foo 对象数组。如何删除数组的第二个元素?
我需要类似于 RemoveAt()
但用于常规数组的东西。
最佳答案
如果你不想使用列表:
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);
关于c# - 删除常规数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/457453/