如何从C#中删除数组中的元素

ahm*_*med 141 .net c# arrays

让我说我有这个阵列,

int[] numbers = {1, 3, 4, 9, 2};
Run Code Online (Sandbox Code Playgroud)

如何通过"名称"删除元素?,让我们说4号?

甚至ArrayList没有帮助删除?

string strNumbers = " 1, 3, 4, 9, 2";
ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' }));
numbers.RemoveAt(numbers.IndexOf(4));
foreach (var n in numbers)
{
    Response.Write(n);
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ter 318

如果要删除所有4的实例而不需要知道索引:

LINQ:(. NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
Run Code Online (Sandbox Code Playgroud)

非LINQ :( .NET Framework 2.0)

static bool isNotFour(int n)
{
    return n != 4;
}

int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();
Run Code Online (Sandbox Code Playgroud)

如果您只想删除第一个实例:

LINQ:(. NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
Run Code Online (Sandbox Code Playgroud)

非LINQ :( .NET Framework 2.0)

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();
Run Code Online (Sandbox Code Playgroud)

编辑:如果你还没有弄清楚,正如Malfist指出的那样,你需要针对.NET Framework 3.5来使LINQ代码示例正常工作.如果您的目标是2.0,则需要参考非LINQ示例.


mee*_*eep 31

int[] numbers = { 1, 3, 4, 9, 2 };
numbers = numbers.Except(new int[]{4}).ToArray();
Run Code Online (Sandbox Code Playgroud)


小智 21

您还可以将数组转换为列表,并在列表中调用remove.然后,您可以转换回您的阵列.

int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);
Run Code Online (Sandbox Code Playgroud)

  • @Deniz \*尤达声音\* 仔细看看,我的朋友。对于数组来说,有比你看到的更多的东西。两者均有效的是“numbersList.Remove(4)”和“numbersList.RemoveAt(4)”!但同样的结果,他们没有给出。 (3认同)

Dev*_*inB 11

写在问题中的代码中有一个错误

你的arraylist包含"1""3""4""9"和"2"的字符串(注意空格)

因此,IndexOf(4)将找不到任何东西,因为4是一个int,甚至"tostring"将它转换为"4"而不是"4",并且什么都不会被删除.

arraylist是正确的方式去做你想要的.


inf*_*net 10

我在这里发布了我的解决方案。

这是一种删除数组元素而不复制到另一个数组的方法 - 就在同一个数组实例的框架中:

    public static void RemoveAt<T>(ref T[] arr, int index)
    {
        for (int a = index; a < arr.Length - 1; a++)
        {
            // moving elements downwards, to fill the gap at [index]
            arr[a] = arr[a + 1];
        }
        // finally, let's decrement Array's size by one
        Array.Resize(ref arr, arr.Length - 1);
    }
Run Code Online (Sandbox Code Playgroud)

  • Resize 实际上是将数据复制到一个新的数组中(除非传入的新大小是传入数组的长度);它不会改变传递的数组实例的大小。这就是为什么它是一个参考参数。请参阅 http://referencesource.microsoft.com/mscorlib/R/71074deaf111c4e3.html。 (4认同)

cta*_*cke 5

从数组中删除并不简单,因为您必须处理调整大小.这是使用类似的东西的巨大优势之一List<int>.它提供Remove/ RemoveAtin 2.0,以及3.0的许多LINQ扩展.

如果可以,重构使用List<>或类似.


Voj*_*vic 5

如果要删除元素的所有实例,Balabaster的答案是正确的.如果你只想删除第一个,你会做这样的事情:

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int firstFoundIndex = Array.IndexOf(numbers, numToRemove);
if (numbers >= 0)
{
    numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray();
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*cio 5

作为通用扩展,2.0 兼容:

using System.Collections.Generic;
public static class Extensions {
    //=========================================================================
    // Removes all instances of [itemToRemove] from array [original]
    // Returns the new array, without modifying [original] directly
    // .Net2.0-compatible
    public static T[] RemoveFromArray<T> (this T[] original, T itemToRemove) {  
        int numIdx = System.Array.IndexOf(original, itemToRemove);
        if (numIdx == -1) return original;
        List<T> tmp = new List<T>(original);
        tmp.RemoveAt(numIdx);
        return tmp.ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

int[] numbers = {1, 3, 4, 9, 2};
numbers = numbers.RemoveFromArray(4);
Run Code Online (Sandbox Code Playgroud)