开发者社区> 问答> 正文

删除常规数组的元素

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

我需要类似于RemoveAt()常规数组的东西。 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-07 22:38:18 462 0
1 条回答
写回答
取消 提交回答
  • 如果您不想使用列表:

    var foos = new List (array); foos.RemoveAt(index); return foos.ToArray(); 您可以尝试我尚未实际测试过的这种扩展方法:

    public static T[] RemoveAt (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-02-07 22:38:29
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
用计算和数据去改变整个世界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载