当前位置: 首页 > news >正文

C#中的集合

集合的介绍

在C#中,集合是存储多个项的数据结构,这些项可以是相同类型或不同类型。C#提供了多种内置集合类型,用于不同的场景和需求。以下是一些常用的集合类型:

  1. 数组(Array)

    • 固定大小的元素序列。

    • 声明时必须指定大小和类型。

    • 例如:int[] numbers = new int[10];

  2. 列表(List<T>)

    • 动态数组,可以根据需要自动调整大小。

    • 允许存储重复的元素。

    • 提供快速的索引访问。

    • 例如:List<int> numbers = new List<int>();

  3. 字典(Dictionary<TKey, TValue>)

    • 基于键值对的集合,每个元素都包含一个键和一个值。

    • 键必须是唯一的,而值则不必。

    • 提供快速的查找速度。

    • 例如:Dictionary<string, int> ageDict = new Dictionary<string, int>();

  4. 队列(Queue<T>)

    • 先进先出(FIFO)的数据结构。

    • 通常用于任务调度和线程同步。

    • 例如:Queue<string> queue = new Queue<string>();

  5. 栈(Stack<T>)

    • 后进先出(LIFO)的数据结构。

    • 通常用于处理具有最后进先出需求的数据。

    • 例如:Stack<int> stack = new Stack<int>();

  6. 集合(HashSet<T>)

    • 包含不重复元素的集合。

    • 提供快速的添加、删除和查找操作。

    • 例如:HashSet<int> numbers = new HashSet<int>();

  7. 排序列表(SortedList<TKey, TValue>)

    • 元素按键排序的字典。

    • 可以按顺序遍历键和值。

    • 例如:SortedList<string, double> sortedScores = new SortedList<string, double>();

  8. 位数组(BitArray)

    • 紧凑的数组,用于表示位(true/false)值。

    • 适合于需要存储大量布尔值的场景。

    • 例如:BitArray bits = new BitArray(32);

  9. 泛型集合

    • C# 2.0引入了泛型集合,如List<T>Dictionary<TKey, TValue>等,它们允许在编译时检查类型安全。

  10. 非泛型集合

    • 泛型出现之前的集合类型,如ArrayListHashtable等,它们不提供编译时类型安全检查。

  11. 可空集合

    • 允许集合中的元素为null,例如List<int?>

  12. 只读集合

    • 一旦创建,集合的内容就不能被修改,例如通过AsReadOnly方法创建的集合。

  13. 并发集合

    • 线程安全的集合,如ConcurrentDictionary<TKey, TValue>,适合在多线程环境中使用。

List集合

List<T> 是 C# 中一个非常常用的泛型集合类,它实现了 IList<T> 接口,提供了列表(动态数组)的数据结构。以下是 List<T> 的一些主要特性和常用操作:

特性:

  • 动态数组List<T> 可以根据需要自动调整大小,这使得它非常适合在不知道具体需要多少元素时使用。

  • 索引访问:可以像数组一样通过索引访问列表中的元素。

  • 类型安全:泛型集合,确保列表中只能存储指定类型的元素。

  • 允许重复:与 HashSet<T> 不同,List<T> 允许存储重复的元素。

  • 有序集合:元素按照添加到列表中的顺序进行排序。

常用操作:

  • 添加元素

    List<int> numbers = new List<int>();
    numbers.Add(1); // 在列表末尾添加一个元素
    numbers.Add(2);

  • 插入元素

    numbers.Insert(0, 0); // 在索引0的位置插入元素0

  • 移除元素

    numbers.Remove(1); // 移除列表中的第一个元素
    numbers.RemoveAt(0); // 移除索引为0的元素

  • 访问元素

    int firstItem = numbers[0]; // 获取索引为0的元素

  • 查找元素

    int index = numbers.IndexOf(2); // 返回元素2的索引,如果不存在则返回-1
    bool contains = numbers.Contains(3); // 检查列表是否包含元素3

  • 遍历列表

    foreach (int number in numbers)
    {Console.WriteLine(number);
    }

  • 获取子列表

    List<int> subList = numbers.GetRange(0, 3); // 获取从索引0开始的3个元素的子列表

  • 反转列表

    numbers.Reverse(); // 将列表中的元素顺序反转

  • 排序列表

    numbers.Sort(); // 默认按升序排序
    // 可以提供自定义的比较器来实现自定义排序
    numbers.Sort((a, b) => a.CompareTo(b));

  • 列表转换

    var squareList = numbers.Select(x => x * x).ToList(); // 使用LINQ将每个元素转换为平方

  • 搜索和过滤

    var evenNumbers = numbers.Where(x => x % 2 == 0).ToList(); // 使用LINQ获取所有偶数

  • 容量和大小

    int count = numbers.Count; // 获取列表中的元素数量
    numbers.Capacity = 100; // 设置列表的容量

  • 清空列表

    numbers.Clear(); // 移除列表中的所有元素

List<T>System.Collections.Generic 命名空间的一部分,因此在代码中使用它时需要包含这个命名空间:

using System.Collections.Generic;

List<T> 是一个非常灵活和强大的集合类,适用于大多数需要动态数组功能的场景。

字典(Dictionary<TKey, TValue>)

Dictionary<TKey, TValue> 是 C# 中一个非常强大的泛型集合类,它存储键值对(key-value pairs),并允许通过键快速访问值。这个类实现了 IDictionary<TKey, TValue> 接口,并且位于 System.Collections.Generic 命名空间中。以下是 Dictionary<TKey, TValue> 的一些主要特性和常用操作:

特性:

  • 基于键值对:每个元素包含一个键和一个相关的值。

  • 快速查找:通过键可以快速检索、添加或删除元素。

  • 键的唯一性:字典中的键必须是唯一的,不允许重复。

  • 无序集合:字典中的元素不保持任何特定的顺序。

常用操作:

  • 初始化字典

    Dictionary<string, int> ageDictionary = new Dictionary<string, int>();

  • 添加元素

    ageDictionary.Add("Alice", 30);
    ageDictionary.Add("Bob", 25);

  • 访问元素

    int age = ageDictionary["Alice"]; // 通过键获取值

  • 检查键是否存在

    if (ageDictionary.ContainsKey("Alice"))
    {// 键存在
    }

  • 移除元素

    ageDictionary.Remove("Bob"); // 移除键为"Bob"的元素

  • 遍历字典

    foreach (KeyValuePair<string, int> pair in ageDictionary)
    {Console.WriteLine("Name: {0}, Age: {1}", pair.Key, pair.Value);
    }

  • 获取键和值的集合

    var keys = ageDictionary.Keys; // 获取所有键的集合
    var values = ageDictionary.Values; // 获取所有值的集合

  • 尝试获取值

    if (ageDictionary.TryGetValue("Alice", out int age))
    {Console.WriteLine($"Alice's age is {age}");
    }

  • 清空字典

    ageDictionary.Clear(); // 移除字典中的所有元素

  • 字典初始化器

    var dictionary = new Dictionary<string, int>
    {{"Alice", 30},{"Bob", 25}
    };

  • 查找和替换

    if (ageDictionary.ContainsKey("Alice"))
    {ageDictionary["Alice"] = 31; // 更新Alice的年龄
    }
    else
    {ageDictionary.Add("Alice", 31); // 如果Alice不存在,添加她
    }

  • 合并字典

    var anotherDictionary = new Dictionary<string, int>
    {{"Charlie", 35},{"David", 40}
    };
    ​
    foreach (var pair in anotherDictionary)
    {ageDictionary.Add(pair.Key, pair.Value);
    }

  • 使用 LINQ 查询字典

    var query = from entry in ageDictionarywhere entry.Value > 30select entry;
    ​
    foreach (var pair in query)
    {Console.WriteLine("Name: {0}, Age: {1}", pair.Key, pair.Value);
    }

Dictionary<TKey, TValue> 是一个非常灵活的数据结构,适用于需要快速查找、添加和删除键值对的场景。使用时,应该确保键的类型重写了 GetHashCode()Equals() 方法,这样可以保证字典的正常工作。


http://www.mrgr.cn/news/25615.html

相关文章:

  • 虚拟存储器“大观”,讲解核心逻辑知识和408大题方法
  • ​​操作系统 ---- 进程调度的时机、切换与过程
  • KV260 进阶开发(PYNQ驱动开发+Pixel Pack)
  • 【时时三省】c语言例题----华为机试题<统计字符>
  • 基于SSM的学生信息管理系统(选课管理系统)的设计与实现 (含源码+sql+视频导入教程)
  • 开发者的噩梦:如何在抄袭狂潮中杀出一条血路?
  • 大模型LLM之SpringAI:Web+AI(二)
  • 求职leetcode题目(10)
  • 机器学习(西瓜书)第 9 章 聚类
  • Netty 相关问题
  • 【Java-简单练习题】
  • C++入门基础
  • HarmonyOS开发实战( Beta5.0)日历切换案例实践详解
  • AI性能评估工具 | 安兔兔AI大模型评测 v1.0.0.1095
  • qml CheckBox 复选框
  • 智能会计定义
  • TCP/IP - Transport Layer
  • Python青少年简明教程:类和对象入门
  • python的特性,以及和Java的区别
  • 如何将任何文本语料转换为知识图谱?