为了账号安全,请及时绑定邮箱和手机立即绑定

删除常规数组的元素

删除常规数组的元素

喵喔喔 2019-07-12 10:24:09
删除常规数组的元素我有一个foo对象数组。如何删除数组的第二个元素?我需要类似的东西RemoveAt()但对于一个普通的数组。
查看完整描述

3 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

如果您不想使用List:

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);


查看完整回答
反对 回复 2019-07-12
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

数组的本质是它们的长度是不可变的。不能添加或删除任何数组项。

您必须创建一个更短的元素的新数组,并将旧项复制到新数组,不包括要删除的元素。

因此,最好使用列表而不是数组。


查看完整回答
反对 回复 2019-07-12
?
12345678_0001

TA贡献1802条经验 获得超5个赞

我使用此方法从对象数组中移除元素。在我的情况下,我的数组长度很小。因此,如果您有大型数组,您可能需要另一种解决方案。

private int[] RemoveIndices(int[] IndicesArray, int RemoveAt){
    int[] newIndicesArray = new int[IndicesArray.Length - 1];

    int i = 0;
    int j = 0;
    while (i < IndicesArray.Length)
    {
        if (i != RemoveAt)
        {
            newIndicesArray[j] = IndicesArray[i];
            j++;
        }

        i++;
    }

    return newIndicesArray;}


查看完整回答
反对 回复 2019-07-12
  • 3 回答
  • 0 关注
  • 363 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信