C# 泛型集合实战:List<T>与Dictionary<TKey, TValue>的使用与优势

C# 中的泛型集合提供了类型安全和性能优势,是现代C#编程中不可或缺的一部分。List<T> 和 Dictionary<TKey, TValue> 是最常用的两个泛型集合类型,分别用于存储元素的列表和键值对的集合。

List

List<T> 是一个可变大小的数组,可以存储任意类型的对象,但一旦声明了List<T>的类型参数T,该列表就只能存储该类型的对象了。List<T>提供了丰富的成员函数来管理集合,如添加、删除、查找元素等。

示例:使用List
csharp 复制代码
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> myList = new List<int>();

        // 添加元素
        myList.Add(1);
        myList.Add(2);
        myList.AddRange(new int[] { 3, 4, 5 });

        // 访问元素
        Console.WriteLine(myList[0]); // 索引访问

        // 遍历List
        foreach (int item in myList)
        {
            Console.WriteLine(item);
        }

        // 使用Linq查询
        var evenNumbers = myList.FindAll(x => x % 2 == 0);
        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}

Dictionary<TKey, TValue>

Dictionary<TKey, TValue> 是一个存储键值对的集合,其中每个键都是唯一的,并且每个键都映射到一个值。Dictionary<TKey, TValue> 提供了快速查找、插入和删除键值对的能力。

示例:使用Dictionary<TKey, TValue>
csharp 复制代码
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> myDict = new Dictionary<string, int>();

        // 添加键值对
        myDict.Add("Apple", 100);
        myDict["Banana"] = 200;

        // 访问元素
        Console.WriteLine($"The count of Apples is {myDict["Apple"]}.");

        // 遍历Dictionary
        foreach (KeyValuePair<string, int> kvp in myDict)
        {
            Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
        }

        // 使用Linq查询
        var filteredDict = myDict.Where(kvp => kvp.Value > 100);
        foreach (var item in filteredDict)
        {
            Console.WriteLine($"Key = {item.Key}, Value = {item.Value}");
        }
    }
}

注意事项

  • 当使用泛型集合时,不需要在添加或检索元素时进行类型转换,因为集合已经知道了它可以存储的元素的类型。
  • 泛型集合比非泛型集合(如ArrayList和Hashtable)提供了更好的性能,因为避免了装箱(boxing)和拆箱(unboxing)操作,并允许更精确的内存分配。
  • 泛型集合也提供了更好的类型安全性,因为编译器可以在编译时检查类型错误。
  • 在选择使用List<T>还是Dictionary<TKey, TValue>时,主要取决于我们的具体需求。如果需要存储一个元素列表并且经常需要按索引访问这些元素,那么List<T>是更好的选择。如果需要存储键值对并经常需要通过键来检索值,那么Dictionary<TKey, TValue>是更合适的选择。
相关推荐
wo_jack3 小时前
C++ 入门笔记(十七):list 入门 —— 为什么 list 不能 sort?
数据结构·c++·面试·stl·list
huaqianzkh6 小时前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
flyingonpine21 小时前
PowerShell脚本数字签名实战:自签名证书、代码签名与信任链验证
windows·信任链
用户3721574261351 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言
goehou1 天前
让 AI 替我操作这台电脑,先把手能伸多远定下来
windows·自动化·权限管理·ai agent
公子小六1 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
三雷科技1 天前
第6章第4节:自定义分词器
开发语言·c#
zhanghaha13141 天前
C# 系列教程_12 字符串 string 保姆级系统教程(面向新手,大量示例 + 原理讲解)
开发语言·数据库·c#
2601_967987372 天前
安装 Redis 或 Redis Stack
linux·windows·redis·macos·安装
Coder_Shenshen2 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#