从C#中的数组中删除数字

问题描述

我正在尝试从数组中删除数字。我尝试按照教程进行操作,该方法删除输入的数字,如果有重复,它将删除一个重复的数字,但是即使数组中的数字不是0,也始终在开始时显示0。例如。说我有一个数字1,12,44,55,66,17,8,4,12,70的列表,我删除了数字44,输出是:0、1,12、55、66、17、8 4,12,70。我不知道为什么会出现0,以及如何消除它。任何帮助将不胜感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace deletenumber
{
class Program
{
    public class Node
    {
        public int data;
        public Node next;
    };

    static Node add(Node head,int data) 
    {
        Node temp = new Node();
        Node current;
        temp.data = data;
        temp.next = null; 

        if (head == null) 
            head = temp;
        else
        {
            current = head;
            while (current.next != null)
                current = current.next;
            current.next = temp; 
        }
        return head;
    }

    static void print(Node head)
    {
        while (head != null) 
        {
            Console.Write(head.data + " "); 
            head = head.next;
        }
    }

    static Node List(int[] a,int n)
    {
        Node head = null; 
        for (int i = 1; i <= n; i++)
            head = add(head,a[i]);
        return head;
    }

    public static void Main(String[] args)
    {
        int n = 10;
        Random r = new Random(); 
        int[] a;
        a = new int[n + 1];
        a[0] = 0;
        int i;

        for (i = 1; i <= n; i++)
            a[i] = r.Next(1,100);

        Node head = List(a,n);
        Console.WriteLine("List = ");

        print(head);
        Console.ReadLine();
        Console.WriteLine();

        Console.WriteLine("What number do you want to delete?");
        int item = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine();

        int index = Array.IndexOf(a,item);
        a = a.Where((e,k) => k != index).ToArray();

        Console.WriteLine(String.Join(",",a));
        Console.ReadLine();
    }
 }
}

解决方法

如果您不想打印0,我不知道为什么要首先添加它,但是请注意“打印”数组的两种不同方式。

第一个方法(print函数)从第1项开始(在索引0处跳过“第一个”元素),并一直循环到结束。

第二个join数组的所有个元素(包括“第一个”元素),并打印结果字符串。

那么您如何跳过零?有很多方法:

  • 首先不要添加零(并将print循环更改为从0开始)

  • 使用从1开始循环的相同打印方法

  • Skip数组中的第一项:

    Console.WriteLine(String.Join(",",a.Skip(1)));
    

就个人而言,我将使用相同的方法两次打印,并且还将使用Array.RemoveAt“删除”该项目,而不是使用Where().ToArray()创建一个新数组。