【C# 数据结构-字典】

在C#中,Dictionary<TKey, TValue> 是一个泛型集合类,属于 System.Collections.Generic 命名空间。它存储了键值对(key-value pairs),允许你使用唯一的键来快速检索、添加、修改和删除元素。

以下是C#中Dictionary<TKey, TValue>的一些基本操作:

初始化:

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

添加元素 - 使用 Add 方法将键值对添加到字典中:

dictionary.Add("key1", 1);

尝试添加元素 - 使用 TryAdd 方法在键不存在时添加键值对:

bool added = dictionary.TryAdd("key2", 2);

访问元素 - 使用索引器通过键访问或设置值:

int value = dictionary["key1"];
dictionary["key1"] = 10; // 更新值

移除元素 - 使用 Remove 方法根据键移除键值对:

bool removed = dictionary.Remove("key1");

检查键是否存在 - 使用 ContainsKey 方法检查字典是否包含特定键:

bool containsKey = dictionary.ContainsKey("key1");

获取键的集合 - 使用 Keys 属性获取字典中所有键的集合:

IEnumerable<string> keys = dictionary.Keys;

获取值的集合 - 使用 Values 属性获取字典中所有值的集合:

IEnumerable<int> values = dictionary.Values;

获取字典中键值对的数量 - 使用 Count 属性:

int count = dictionary.Count;

清空字典 - 使用 Clear 方法:

dictionary.Clear();

遍历字典 - 使用 foreach 循环遍历字典中的所有键值对:

foreach (KeyValuePair<string, int> kvp in dictionary)
{
    Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}

查找具有特定键的值 - 使用 this 索引器或 TryGetValue 方法:

int value;
bool found = dictionary.TryGetValue("key2", out value);

下面是一个简单的C# Dictionary<TKey, TValue> 使用示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> dictionary = new Dictionary<string, int>
        {
            {"key1", 1},
            {"key2", 2}
        };

        // 添加元素
        dictionary.Add("key3", 3);

        // 尝试添加元素
        bool added = dictionary.TryAdd("key4", 4);

        // 访问元素
        int value1 = dictionary["key1"];
        dictionary["key1"] = 10; // 更新值

        // 移除元素
        bool removed = dictionary.Remove("key3");

        // 检查键是否存在
        bool containsKey = dictionary.ContainsKey("key1");

        // 获取键的集合
        IEnumerable<string> keys = dictionary.Keys;

        // 获取值的集合
        IEnumerable<int> values = dictionary.Values;

        // 打印键和值
        foreach (KeyValuePair<string, int> kvp in dictionary)
        {
            Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
        }

        // 获取字典中键值对的数量
        int count = dictionary.Count;

        // 清空字典
        dictionary.Clear();

        Console.WriteLine("Count after clearing: " + dictionary.Count);
    }
}

想了解更多游戏开发知识,可以扫描下方二维码,免费领取游戏开发4天训练营课程
在这里插入图片描述

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值