删除常规数组的元素 [英] Remove element of a regular array
本文介绍了删除常规数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组 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.
推荐答案
如果不想使用 List:
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);
这篇关于删除常规数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文