自学内容网 自学内容网

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

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

List

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

示例:使用List
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>
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}");
        }
    }
}

注意事项

  • 当使用泛型集合时,不需要在添加或检索元素时进行类型转换,因为集合已经知道了它可以存储的元素的类型。
  • 泛型集合比非泛型集合(如ArrayListHashtable)提供了更好的性能,因为避免了装箱(boxing)和拆箱(unboxing)操作,并允许更精确的内存分配。
  • 泛型集合也提供了更好的类型安全性,因为编译器可以在编译时检查类型错误。
  • 在选择使用List<T>还是Dictionary<TKey, TValue>时,主要取决于我们的具体需求。如果需要存储一个元素列表并且经常需要按索引访问这些元素,那么List<T>是更好的选择。如果需要存储键值对并经常需要通过键来检索值,那么Dictionary<TKey, TValue>是更合适的选择。

原文地址:https://blog.csdn.net/x1234w4321/article/details/142180803

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!