在 C# 中对比KeyValuePair<TKey, TValue> 和 IDictionary<TKey, TValue>

C# 中的 KeyValuePair<TKey, TValue> 和 IDictionary<TKey, TValue> 具有独特的用途并表现出不同的特征。

KeyValuePair<TKey, TValue> 的功能

KeyValuePair<TKey, TValue> 是存储单个键值对的数据结构。它属于 System.Collections.Generic 命名空间。

用法

  • 它用于表示单个键值对,通常在枚举的上下文中或当需要从方法返回多个值时。

  • 经常与实现键值对的集合一起使用,例如字典,但也可以单独使用。

不变性

创建后,KeyValuePair 的键和值无法修改,因为其属性是只读的(DotNetPerls)。

特性

  • Key:获取键值对中的键。
  • Value:获取键值对中的值。

注意: KeyValuePair<TKey, TValue> 可能包含重复的键。

例子

// 导入 System.Windows 命名空间以使用 WPF 功能。
using System.Windows; 

// 导入 System.Collections.Generic 命名空间以使用泛型集合。
using System.Collections.Generic; 

// 导入 System 命名空间以使用基本功能,如 Console。
using System; 

// 定义应用程序的命名空间。
namespace KeyValuePairDictionaryExample 
{
    // MainWindow.xaml 的交互逻辑
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    // MainWindow 类继承自 Window,Window 是 WPF 窗口的基类。
    public partial class MainWindow : Window 
    {
        // MainWindow 的构造函数。
        public MainWindow() 
        {
            // 初始化组件(由 WPF 设计器生成)。
            InitializeComponent(); 
            // 调用方法生成并显示键值对列表。
            GenerateKeyValuePairList(); 
        }

        // 方法生成一个键值对列表。
        private void GenerateKeyValuePairList() 
        {
            // 创建一个存储 KeyValuePair<string, string> 对象的列表。
            List<KeyValuePair<string, string>> keyValuePairsList = new List<KeyValuePair<string, string>>();

            // 添加初始的键值对到列表中。
            keyValuePairsList.Add(new KeyValuePair<string, string>("firstKey", "First Value")); 
            // 添加第一个键值对。
            keyValuePairsList.Add(new KeyValuePair<string, string>("secondKey", "Second Value")); 
            // 添加第二个键值对。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Third Value")); 
            // 添加第三个键值对。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Fourth Value")); 
            // 添加第四个键值对,键与前一个相同。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Fifth Value")); 
            // 添加第五个键值对,键与前一个相同。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Sixth Value")); 
            // 添加第六个键值对,键与前一个相同。

            // 创建一个列表存储要添加的新键值对。
            List<KeyValuePair<string, string>> itemsToAddToExistingList = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("fourthKey", "Seventh Value"), 
                // 创建并添加第七个键值对。
                new KeyValuePair<string, string>("fifthKey", "Eighth Value") 
                // 创建并添加第八个键值对。
            };

            // 将新键值对添加到原始列表中。
            foreach (var kvp in itemsToAddToExistingList) 
            // 遍历每个新键值对。
            {
                keyValuePairsList.Add(kvp); 
                // 将当前键值对添加到原始列表中。
            }

            // 调用方法显示所有键值对。
            ShowKeyValuePairs(keyValuePairsList);
        }

        // 方法显示键值对。
        private void ShowKeyValuePairs(List<KeyValuePair<string, string>> keyValuePairsList) 
        {
            // 遍历列表中的每个键值对。
            foreach (KeyValuePair<string, string> kvp in keyValuePairsList) 
            {
                // 输出键值对到控制台。
                Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); 
            }
        }
    }
}

Dictionary<TKey, TValue> 的功能

Dictionary<TKey, TValue> 类负责管理一组键值对。它是 System.Collections.Generic 命名空间的一个组件。

用途

此类的主要用途是存储多个键值对,确保每个键都是唯一的。它提供了检索、添加和删除这些对的高效操作。

可变性

就可变性而言,您可以在字典中添加、删除和更新元素。

用法

当您需要管理数据集合时通常使用此类,其中每个元素由唯一的键标识。

例子

using System;
// 导入 System 命名空间以使用基本功能,如 Console。

using System.Windows;
// 导入 System.Windows 命名空间以使用 WPF 功能。

using System.Collections.Generic;
// 导入 System.Collections.Generic 命名空间以使用泛型集合。

namespace KeyValuePairDisctionaryExample
// 定义应用程序的命名空间。
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    // MainWindow 类继承自 Window,Window 是 WPF 窗口的基类。
    {
        public MainWindow()
        // MainWindow 的构造函数。
        {
            InitializeComponent();
            // 初始化组件(由 WPF 设计器生成)。
            GenerateDictionary();
            // 调用方法生成并显示字典。
        }

        private void GenerateDictionary()
        // 方法生成一个字典。
        {
            Dictionary<string, string> dictCollection = new Dictionary<string, string>
            // 创建一个存储键值对的字典。
            {
                {"firstKey", "First Value"},
                // 添加第一个键值对。
                {"secondKey", "Second value"},
                // 添加第二个键值对。
                {"ThirdKey", "Third Value"},
                // 添加第三个键值对。
                {"FourthKey", "Fourth Value"}
                // 添加第四个键值对。
            };

            dictCollection.Add("FifthKey", "FifthValue");
            // 添加第五个键值对。

            if (dictCollection.ContainsKey("secondKey"))
            // 检查字典是否包含键 "secondKey"。
            {
                Console.WriteLine(dictCollection["secondKey"]);
                // 输出键 "secondKey" 对应的值:Second value。
            }

            foreach (var kvp in dictCollection)
            // 遍历字典中的每个键值对。
            {
                Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
                // 输出键值对到控制台。
            }
        }
    }
}

注意:在字典中,不允许有重复的键。

相关推荐
时光追逐者几秒前
分享6个.NET开源的AI和LLM相关项目框架
人工智能·microsoft·ai·c#·.net·.netcore
宇卿.6 分钟前
Java键盘输入语句
java·开发语言
Amo Xiang15 分钟前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
friklogff28 分钟前
【C#生态园】提升C#开发效率:深入了解自然语言处理库与工具
开发语言·c#·区块链
重生之我在20年代敲代码2 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文2 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286115 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py5 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy5 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript