详解C#中一维数组的插入

时间:2022-06-02 17:21:23

一维数组的插入:

实现效果:在1 2 3 后面插入4

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Array
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] array = new int[] { 1, 2, 3 };
      int[] des = addArray(array, 4, 4);
      foreach (int item in des)
      {
        Console.WriteLine(item );
      }
      Console.ReadLine();
    }
    static int[] addArray(int[] bornArray, int index, int value)
    {
      ArrayList list = new ArrayList(bornArray );
      if (index <0)
      {
        index =0 ;
      }
      if (index >bornArray .Length -1)
      {
        index = bornArray.Length;
      }
      list.Insert(index ,value );
      int[] des = new int[list.Count ];
      for (int i=0;i<list.Count;i++)
      {
        des[i] = (int)list[i];
      }
      return des;
    }
  }
}

原文链接:https://www.idaobin.com/archives/950.html