C#数组如何添加元素

C#数组如何添加元素,第1张

1、使用 ArrayList 来定义数组,Arraylist  有add、Insert方法,可以自由向数组中添加新数据。

2、向数组中增加一个元素,运行数组测试程序,并向控制台输出结果,

arraylist.Add(5)// 添加数组元素

Console.WriteLine("2. 数组列表的容量为{0},实际包含{1}个元素:",

              arraylist.Capacity, arraylist.Count)

3、如果要向数组中批量增加数据,可以使用AddRange来实现:

arraylist.AddRange(new int[] { 6, 7, 8 })// 在ArrayList末尾批量添加元素  。

4、如果要向数组的指定位置添加数据,可以使用Insert方法来实现:

 arraylist.Insert(3, 88)//添加数组元素。

5、如果不用ArrayList来定义数组,则将发现数组是固定的,那么可以人工给数据“变长”;用连接两个数组函数Concat,以及创建数组函数ToArray完成数组添加数据的任务。

6、通过 “x = x.Concat(new int[] { 5,6 }).ToArray()”添加数据,运行数组测试程序,并向控制台输出结果。

楼上都是在哪复制的 ?

很简单的一个问题 是动态数组 几位大哥!

ArrayList al=new ArrayList()//创建

al.Add("1")//添加

al.Add("2")//.

foreach(string s in al)//遍历数组

Console.write(s) //输出 1 2

回答完毕 接分

继续你的问题

比如说 string []s=new string {1,2,3,4,5}

for(int i=0i<s.counti++)

{

al.add(s[i])

}

//al就是动态数组

将数组转换成List<T>后,利用List<T>.Insert实现插入新元素。方法如下:

using System

using System.Collections.Generic

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

int[] x = { 1, 2, 3, 4 }

Console.WriteLine("插入前")

PrintArray(x)

try

{

x = InsertNumber(x, 10, 4)

Console.WriteLine("在 Index=4 处插入10后")

PrintArray(x)

x = InsertNumber(x, 100, 0)

Console.WriteLine("在 Index=0 处插入100后")

PrintArray(x)

}

catch (Exception e)

{

Console.WriteLine(e.Message)

}

}

/// <summary>

/// 将value 插入到指定数组的指定的位置

/// </summary>

/// <param name="a">指定数组</param>

/// <param name="value">待插入的元素</param>

/// <param name="index">插入的位置</param>

/// <returns>插入后的数组</returns>

static int[] InsertNumber(int[] a, int value, int index)

{

try

{

//转换成List<int>集合

List<int>list = new List<int>(a)

//插入

list.Insert(index, value)

//从List<int>集合,再转换成数组

return list.ToArray()

}

catch (Exception e)  // 捕获由插入位置非法而导致的异常

{

throw e

}

}

/// <summary>

/// 打印数组

/// </summary>

static void PrintArray(int[] a)

{

foreach (int x in a)

{

Console.Write("{0} ", x)

}

Console.WriteLine()

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11352822.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-15
下一篇2023-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存