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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/496896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:41:48  来源:igfitidea点击:

How to delete an element from an array in C#

c#.netarrays

提问by ahmed

Lets say I have this array,

假设我有这个数组,

int[] numbers = {1, 3, 4, 9, 2};

How can I delete an element by "name"? , lets say number 4?

如何通过“名称”删除元素?,让我们说数字 4?

Even ArrayListdidn't help to delete?

甚至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);
}

采纳答案by BenAlabaster

If you want to remove all instances of 4 without needing to know the index:

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

LINQ:(.NET Framework 3.5)

LINQ:(.NET 框架 3.5)

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

Non-LINQ:(.NET Framework 2.0)

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

If you want to remove just the first instance:

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

LINQ:(.NET Framework 3.5)

LINQ:(.NET 框架 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();

Non-LINQ:(.NET Framework 2.0)

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

Edit:Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.

编辑:以防万一您还没有弄清楚,正如 Malfist 指出的那样,您需要以 .NET Framework 3.5 为目标,以便 LINQ 代码示例工作。如果您的目标是 2.0,则需要参考非 LINQ 示例。

回答by ctacke

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int>instead. It provides Remove/RemoveAtin 2.0, and lots of LINQ extensions for 3.0.

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

If you can, refactor to use a List<>or similar.

如果可以,重构为使用 aList<>或类似的。

回答by Vojislav Stojkovic

Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:

如果要删除元素的所有实例,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();
}

回答by DevinB

The code that is written in the question has a bug in it

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

Your arraylist contains strings of " 1" " 3" " 4" " 9" and " 2" (note the spaces)

您的数组列表包含“1”“3”“4”“9”和“2”的字符串(注意空格)

So IndexOf(4) will find nothing because 4 is an int, and even "tostring" would convert it to of "4" and not " 4", and nothing will get removed.

所以 IndexOf(4) 什么也找不到,因为 4 是一个整数,甚至“tostring”也会将它转换为“4”而不是“4”,并且不会删除任何内容。

An arraylist is the correct way to go to do what you want.

arraylist 是做你想做的事情的正确方法。

回答by Dave DP

You can also convert your array to a list and call remove on the list. You can then convert back to your array.

您还可以将数组转换为列表并在列表上调用 remove。然后您可以转换回您的数组。

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

回答by meetjaydeep

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

回答by SP007

' To remove items from string based on Dictionary key values.' VB.net code

'根据字典键值从字符串中删除项目。' VB.net 代码

 Dim stringArr As String() = "file1,file2,file3,file4,file5,file6".Split(","c)
 Dim test As Dictionary(Of String, String) = New Dictionary(Of String, String)
 test.Add("file3", "description")
 test.Add("file5", "description")
 stringArr = stringArr.Except(test.Keys).ToArray()

回答by Petrucio

As a generic extension, 2.0-compatible:

作为通用扩展,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();
    }
}

Usage:

用法:

int[] numbers = {1, 3, 4, 9, 2};
numbers = numbers.RemoveFromArray(4);

回答by infografnet

I posted my solution here.

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

This is a way to delete an array element without copying to another array - just in frame of the same array instance:

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

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

回答by infografnet

You can do in this way:

你可以这样做:

int[] numbers= {1,3,4,9,2};     
List<int> lst_numbers = new List<int>(numbers);
int required_number = 4;
int i = 0;
foreach (int number in lst_numbers)
{              
    if(number == required_number)
    {
        break;
    }
    i++;
}
lst_numbers.RemoveAt(i);
numbers = lst_numbers.ToArray();