如何删除数组中的选定元素?

use*_*065 13 c# arrays

我有这个任务,我必须从数组中删除一个选定的元素,所以我想出了这个代码:

strInput = Console.ReadLine();
for (int i = 0; i < intAmount; i++)
{
    if (strItems[i] == strInput)
    {
        strItems[i] = null;
        for (int x = 0; x < intAmount-i; x++)
        {
            i = i + 1;
            strItems[i - 1] = strItems[i];
        }
        intAmount = intAmount - 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,假设我有一个数组[1,2,3,4,5,],我想删除1.输出将是[2,3,4,5,5].当我选择时也会发生这种情况2,但是当我选择任何其他数字时它不会发生.

我究竟做错了什么?

Cᴏʀ*_*ᴏʀʏ 39

我假设你正在使用一个基本的字符串数组:

var strItems = new string[] { "1", "2", "3", "4", "5" };
Run Code Online (Sandbox Code Playgroud)

在.NET中,该数组总是长5个元素.要删除元素,您必须将其余元素复制到新数组并返回它.将值设置为null不会将其从数组中删除.

现在,像LINQ这样的东西很容易(这里没有显示),或者你可以使用该List<>集合作弊并执行此操作:

var list = new List<string>(strItems);
list.Remove("3");
strItems = list.ToArray();
Run Code Online (Sandbox Code Playgroud)

但我认为这不会教会你什么.

第一步是找到要删除的元素的索引.你可以Array.IndexOf用来帮助你.让我们找到中间元素"3":

int removeIndex = Array.IndexOf(strItems, "3");
Run Code Online (Sandbox Code Playgroud)

如果找不到该元素,它将返回-1,因此在执行任何操作之前检查该元素.

if (removeIndex >= 0)
{
     // continue...
}
Run Code Online (Sandbox Code Playgroud)

最后,您必须将元素(除了我们不想要的索引之外的元素)复制到新数组.所以,总而言之,你最终得到这样的东西(评论说明):

string strInput = Console.ReadLine();
string[] strItems = new string[] { "1", "2", "3", "4", "5" };

int removeIndex = Array.IndexOf(strItems, strInput);

if (removeIndex >= 0)
{
    // declare and define a new array one element shorter than the old array
    string[] newStrItems = new string[strItems.Length - 1];

    // loop from 0 to the length of the new array, with i being the position
    // in the new array, and j being the position in the old array
    for (int i = 0, j = 0; i < newStrItems.Length; i++, j++)
    {
        // if the index equals the one we want to remove, bump
        // j up by one to "skip" the value in the original array
        if (i == removeIndex)
        {
            j++;
        }

        // assign the good element from the original array to the
        // new array at the appropriate position
        newStrItems[i] = strItems[j];
    }

    // overwrite the old array with the new one
    strItems = newStrItems;
}
Run Code Online (Sandbox Code Playgroud)

现在strItems将是新数组,减去指定的删除值.