c# - 删除常规数组的元素

标签 c# .net arrays

我有一个 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/

相关文章:

.net - .Net 1.1 Windows 的 RTF 控件

javascript - 在 javascript 中的命名对象数组中 - 名称可以访问吗?

ios - Swift - 如何查找数组中数组中项目的索引

c# - 函数参数中的C#列表

c# - 反复按下按钮时,ColorAnimation 停留在颜色上

c# - 通过 C# RESI API 传递 Json 后,PHP 网页显示空字符串

c# - Rhino Mocks Restub 功能

c# - 如何通过 LINQ 展平树?

arrays - 将项目移动到集合开头的最佳方法

c# - 存储网络服务的密码?