c# 中List的介绍说明

一.List的定义说明

在C#中,List<T>是一个泛型类,它允许你创建一个元素类型为T的强类型列表。List<T>类位于System.Collections.Generic命名空间下,是.NET Framework的一部分。

二.List<T>的一些常用操作和方法

2.1添加元素:

2.1.1 Add(T item):将对象添加到List中;

2.1.2 AddRange(IEnumerable<T> collection):添加集合中的元素到List中;

2.2插入元素:

2.2.2 Insert(int index, T item):在指定的位置index插入元素item;

2.3删除元素:

2.3.1 Remove(T item):移除特定的对象,如果列表中有多个该对象,只会移除第一个;

2.3.2 RemoveAt(int index):移除指定索引处的元素;

2.3.3 RemoveAll(Predicate<T> match):移除所有匹配条件的元素;

2.3.4 Clear():移除所有元素;

2.4查找元素:

2.4.1 Contains(T item):判断是否包含特定的对象;

2.4.2 IndexOf(T item):返回对象的索引,如果列表中有多个该对象,只会返回第一个的索引;

2.4.3 FindIndex(Predicate<T> match):返回匹配特定条件的元素的索引;

2.4.4 Find(Predicate<T> match):返回匹配特定条件的第一个元素;

2.5排序:

2.5.1 Sort():对列表进行排序;

2.5.2 Reverse():反转列表中元素的顺序;

2.6转换和复制:

2.6.1 ToArray():将List转换为数组;

2.6.2 CopyTo(T[] array):将List中的元素复制到一个新的数组中;

2.7统计和求和:

2.7.1 Sum(Func<T, int> selector):计算集合中元素的和;

2.7.2 Average(Func<T, int> selector):计算集合中元素的平均值;

三.List<T>的简单示例

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static void Main()
    {
        List<int> numbers = new List<int>();
 
        // 添加元素
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);
 
        // 插入元素
        numbers.Insert(2, 4);
 
        // 查找元素
        bool contains3 = numbers.Contains(3); // 返回 true
        int indexOf4 = numbers.IndexOf(4); // 返回 2
 
        // 移除元素
        numbers.Remove(2);
        numbers.RemoveAt(0);
 
        // 统计和求和
        int sum = numbers.Sum(); // 使用默认的加法选择器
        double average = numbers.Average(); // 使用默认的加法选择器
 
        // 打印结果
        Console.WriteLine("Sum: " + sum);
        Console.WriteLine("Average: " + average);
 
        // 转换和复制
        int[] array = numbers.ToArray();
        numbers.CopyTo(array);
 
        // 排序和反转
        numbers.Sort();
        numbers.Reverse();
 
        // 打印排序和反转后的结果
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

四.注意事项

4.1 List 是一个基于索引的集合,这意味着元素是按顺序存储的;

4.2 List 的容量可以动态增长,但如果需要增加容量,则会影响性能;

4.3 使用 List 时,确保考虑内存消耗,因为它是存储在堆上的;

相关推荐
lly2024067 小时前
HTML与CSS:构建网页的基石
开发语言
一只会写代码的猫7 小时前
面向高性能计算与网络服务的C++微内核架构设计与多线程优化实践探索与经验分享
java·开发语言·jvm
是小胡嘛9 小时前
C++之Any类的模拟实现
linux·开发语言·c++
csbysj202010 小时前
Vue.js 混入:深入理解与最佳实践
开发语言
0***1410 小时前
PHP在微服务中的架构设计
微服务·云原生·架构
uzong11 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
Gerardisite11 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want59511 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan12 小时前
【C++】多态
开发语言·c++
gfdhy12 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希