C# 数组对象添加和删除元素

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
 
namespace _1207_数组删除元素
{
    class Program
    {        
        //只能在动态数组ArrayList类中对数组执行删除元素的操作。
        //因为动态数组是一个可以改变数组长度和元素个数的数据类型。
        //为Program类定义一个静态方法Show
        public static void Show(ArrayList alist)
        {
            for (int i = 0; i < alist.Count; i++)
            {
                Console.Write("[{0}]:{1} ", i, alist[i]);
            }
            Console.WriteLine("\n");
        }
        static void Main(string[] args)
        {
            // C#数组删除元素
            ArrayList arraylist = new ArrayList();
            for (int i = 0; i < 7; i++)
            {
                arraylist.Add(i);
            }
            Console.WriteLine("1. 数组列表的容量为{0},实际包含{1}个元素:",
                arraylist.Capacity, arraylist.Count);
            Show(arraylist);
            arraylist.Remove(3);   // 删除数组元素
            arraylist.RemoveAt(5); // 删除指定索引位置5的元素
            Console.WriteLine("2. 数组列表的容量为{0},实际包含{1}个元素:",
                arraylist.Capacity, arraylist.Count);
            Show(arraylist);
            Console.ReadLine();
        }
    }
}
 
复制代码

附: 声明数组的方法:

//定义数组
数据类型[]  数组名;

//初始化数组中的元素
数据类型[]  数组名 = new  数据类型[长度];
数据类型[]  数组名 = {值 1, 值 2, ...}
数据类型[]  数组名 = new  数据类型[长度]{值 1,值 2,...}

 

1
2
3
4
5
6
//定义 int 类型的数组
int[] a = {1,2,3};
//输岀数组中的一个元素
Console.WriteLine(a[0]);
//输出数组中的最后一个元素
Console.WriteLine(a[a.Length-1]);

  

posted @   朝阳的向日葵  阅读(9478)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示