c# 学习笔记 - 集合(Dictionary)

文章目录

    • 1.概论
      • [1.1 Dictionary 特性](#1.1 Dictionary 特性)
      • [1.2 .NET API](#1.2 .NET API)
    • [2. 基本使用](#2. 基本使用)
      • [2.1 样例](#2.1 样例)
    • [3. 添加类操作](#3. 添加类操作)
      • [3.1 Add、TryAdd](#3.1 Add、TryAdd)
    • [4. 修改类操作](#4. 修改类操作)
      • [4.1 Remove、Clear](#4.1 Remove、Clear)

1.概论

1.1 Dictionary 特性

  • 1. 键值对容器,底层使用哈希表实现.
  • 2. 键唯一,不可以重复添加.

1.2 .NET API

**  API介绍**
Dictionary<TKey,TValue> 类

2. 基本使用

2.1 样例

csharp 复制代码
static void Main() {
    Dictionary<int, string> dic = new Dictionary<int, string>();

    dic.Add(1, "AA"); // 新增
    dic.Add(2, "BB");
    foreach(var item in dic) Console.WriteLine(item.Key + " " + item.Value);
    Console.WriteLine("=======================================");

    dic[1] = "CC"; // 修改 dic[key] = value; 
    foreach(var item in dic) Console.WriteLine(item.Key + " " + item.Value);
    Console.WriteLine("=======================================");


    dic.Remove(1); // 删除
    foreach(var item in dic) Console.WriteLine(item.Key + " " + item.Value);
    Console.WriteLine("=======================================");
}
/*
1 AA
2 BB
=======================================
1 CC
2 BB
=======================================
2 BB
=======================================
*/

3. 添加类操作

3.1 Add、TryAdd

  • Add -- 添加指定键值对
  • TryAdd -- 尝试添加指定键值对
csharp 复制代码
static void Main() {
    Dictionary<int, string> dic = new Dictionary<int, string>();

    dic.Add(1, "AA");
    dic.Add(2, "BB");
    Console.WriteLine(dic.TryAdd(2, "B2"));
    Console.WriteLine(dic.TryAdd(3, "CC"));
    foreach(var item in dic) {
        Console.WriteLine(item.Key + " " + item.Value);
    }
}

/*
False
True
1 AA
2 BB
3 CC
*/

4. 修改类操作

4.1 Remove、Clear

  • Remove -- 清除指定键值对
  • Clear-- 删除所有键值对
csharp 复制代码
static void Main() {
    Dictionary<int, string> dic = new Dictionary<int, string>();

    dic.Add(1, "AA");
    dic.Add(2, "BB");
    dic.Add(3, "CC");
    dic.Remove(2); // Remove(key)
    foreach(KeyValuePair<int, string> item in dic) {
        Console.WriteLine(item.Key + " " + item.Value);
    }

    dic.Clear();
    foreach(KeyValuePair<int, string> item in dic) {
        Console.WriteLine(item.Key + " " + item.Value);
    }
}

/*
1 AA
3 CC
*/
相关推荐
菜鸟‍23 分钟前
【论文学习】Segment Anything 分割一切
深度学习·学习·计算机视觉
殇淋狱陌1 小时前
Python列表知识思维导图
开发语言·python·学习
fox_lht1 小时前
第十五章 函数式语言:迭代器和闭包
开发语言·后端·学习·算法·rust
LeeAmos11 小时前
Addendum No. 1 to JESD209-4 Low Power Double Data Rate 4X (LPDDR4X)的中文版
笔记
2301_775602382 小时前
食品安全法
学习
xiaoshuaishuai82 小时前
C# vCenter跨云迁移的核心问题
开发语言·c#
踏着七彩祥云的小丑2 小时前
嵌入式测试学习第33 天:压力测试、反复开关机、反复插拔接口测试
单片机·嵌入式硬件·学习
旧物有情2 小时前
C#异步编程
网络·rpc·c#
fox_lht2 小时前
14.6.将错误重定向到标准错误
开发语言·后端·学习·rust
fanged3 小时前
Linux内核学习17--SPI子系统(TODO)
学习