C#集合与泛型

本文介绍了C#中几种主要的集合类型,包括ArrayList、List、SortedList等的使用方法,如添加、删除、查找元素等操作。同时,文章也探讨了泛型的概念,如何通过泛型提高代码复用性和安全性,并展示了泛型接口、泛型类和泛型方法的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、集合:专门用来数组存储和检索

泛型集合:List(通过索引访问元素)、Dictionary(通过key访问元素)、

非泛型集合:ArrayList(通过索引访问元素)、Hashtable(通过key访问元素)、BitArray(通过整型索引访问)

既有泛型又有非泛型:SortedList(通过索引和key访问元素)、Stack、Queue

1.ArrayList:动态数组。当中间元素被删除时,后面的元素会前移

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

namespace CollectionTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrayList = new ArrayList();
            //常用方法
            arrayList.Add(123);//添加元素
            arrayList.Insert(1, "动态数组");//在指定索引处插入元素
            arrayList.Remove(123);//移除元素
            arrayList.RemoveAt(0);//移除指定索引处的元素
            Console.WriteLine(arrayList.Contains("动态数组"));//判断是否包含某元素
            Console.WriteLine(arrayList.IndexOf("动态数组"));//获取某元素的索引
            arrayList.Reverse();//逆置动态数组中的元素
            arrayList.Sort();//对动态数组排序
            arrayList.Clear();//清空元素
            //arraylist.ToArray(); 将arraylist转为数组
            //常用属性
            int num=arrayList.Count;//动态数组中实际的元素个数
            arrayList[0] = 123;//获取或设置指定索引的元素 
        }
    }
}

更多内容:C# 动态数组(ArrayList) | 菜鸟教程

2.List:链表。当中间元素被删除时,后面的元素会前移

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

namespace CollectionTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();
            //常用方法
            list.Add(123);//添加元素
            list.Insert(1, 234);//在指定索引处插入元素
            list.Remove(123);//移除元素
            list.RemoveAt(0);//移除指定索引处的元素
            Console.WriteLine(list.Contains(234));//判断是否包含某元素
            Console.WriteLine(list.IndexOf(234));//获取某元素的索引
            list.Reverse();//逆置动态数组中的元素
            list.Sort();//对动态数组排序
            list.Clear();//清空元素
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寒冷的晚风

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值