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

C# 里的 KeyValuePair<TKey, TValue>

我们来详细讲讲 C# 里的 KeyValuePair<TKey, TValue> —— 它是键值对(key-value pair)的基础类型,在字典(Dictionary<TKey, TValue>)中非常常见。


🔹 一、概念说明

KeyValuePair<TKey, TValue> 是一个结构体,定义在命名空间:


using System.Collections.Generic;

它包含两个只读属性:

  • Key:键(TKey)

  • Value:值(TValue)


🔹 二、常见用法

✅ 示例 1:创建 KeyValuePair

using System;
using System.Collections.Generic;class Program
{static void Main(){var pair = new KeyValuePair<int, string>(1, "Apple");Console.WriteLine($"Key = {pair.Key}, Value = {pair.Value}");}
}

输出:

Key = 1, Value = Apple

✅ 示例 2:遍历 Dictionary(最常见)

var dict = new Dictionary<int, string>
{{1, "Apple"},{2, "Banana"},{3, "Cherry"}
};foreach (KeyValuePair<int, string> kvp in dict)
{Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}

输出:

Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Cherry

💡foreach 遍历 Dictionary 时,每个元素就是一个 KeyValuePair<TKey, TValue>


✅ 示例 3:配合 LINQ 使用

using System.Linq;var dict = new Dictionary<string, int>
{{"Tom", 80},{"Bob", 90},{"Alice", 95}
};// 按值排序
var sorted = dict.OrderByDescending(kvp => kvp.Value);foreach (var kvp in sorted)
{Console.WriteLine($"{kvp.Key} => {kvp.Value}");
}

✅ 示例 4:用 KeyValuePair 构造 Dictionary

var pairs = new List<KeyValuePair<string, int>>
{new KeyValuePair<string, int>("A", 100),new KeyValuePair<string, int>("B", 200)
};var dict = pairs.ToDictionary(p => p.Key, p => p.Value);

🔹 三、KeyValuePair vs DictionaryEntry

特性KeyValuePair<TKey, TValue>DictionaryEntry
泛型✅ 是❌ 否
命名空间System.Collections.GenericSystem.Collections
推荐用法推荐用于 Dictionary<TKey, TValue>仅用于 Hashtable 等老式集合

🔹 四、典型场景(在项目中)

例如你要返回一组键值对应关系(例如版本号和名字):

List<KeyValuePair<long, string>> versionList = new()
{new KeyValuePair<long, string>(1001, "V1.0"),new KeyValuePair<long, string>(1002, "V2.0"),
};

或者在循环中临时收集数据:

var results = new List<KeyValuePair<string, int>>();foreach (var user in users)
{results.Add(new KeyValuePair<string, int>(user.Name, user.Score));
}

✅ 总结

功能示例
创建new KeyValuePair<int, string>(1, "A")
获取键pair.Key
获取值pair.Value
遍历字典foreach (var kvp in dict)
构建集合List<KeyValuePair<string,int>>
转换成字典.ToDictionary(p => p.Key, p => p.Value)

源码:

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;namespace System.Collections.Generic
{// Provides the Create factory method for KeyValuePair<TKey, TValue>.public static class KeyValuePair{// Creates a new KeyValuePair<TKey, TValue> from the given values.public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value) =>new KeyValuePair<TKey, TValue>(key, value);/// <summary>Used by KeyValuePair.ToString to reduce generic code</summary>internal static string PairToString(object? key, object? value) =>string.Create(null, stackalloc char[256], $"[{key}, {value}]");}// A KeyValuePair holds a key and a value from a dictionary.// It is used by the IEnumerable<T> implementation for both IDictionary<TKey, TValue>// and IReadOnlyDictionary<TKey, TValue>.[Serializable][TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]public readonly struct KeyValuePair<TKey, TValue>{[DebuggerBrowsable(DebuggerBrowsableState.Never)]private readonly TKey key; // Do not rename (binary serialization)[DebuggerBrowsable(DebuggerBrowsableState.Never)]private readonly TValue value; // Do not rename (binary serialization)public KeyValuePair(TKey key, TValue value){this.key = key;this.value = value;}public TKey Key => key;public TValue Value => value;public override string ToString(){return KeyValuePair.PairToString(Key, Value);}[EditorBrowsable(EditorBrowsableState.Never)]public void Deconstruct(out TKey key, out TValue value){key = Key;value = Value;}}
}

仅供学习参考,如有侵权联系我删除。

http://www.dtcms.com/a/507496.html

相关文章:

  • Speckit 简明教程
  • 明知手机忘带却不着急回去拿,因为可以远程控制
  • 深入理解 CSS 表格布局:table-layout 的秘密与实战详解(附费用报销单案例)
  • rsync+sersync实现数据实时双向同步
  • ppt模板去哪个网站下载德州核酸检测最新公告
  • 迅为RK3568开发板OpenHarmony系统南向驱动开发手册-UART应用开发编译源码
  • java面试-0216-HashMap和LinkedHashMap、TreeMap、HashTable√、ConcurrentHashMap区别?
  • 【文献分享】KADAIF:一种针对复杂微生物组数据的异常检测方法
  • React Native开发AndroidIOS流程完整指南
  • 身份证实名认证接口在金融领域的应用:筑牢风控第一道防线
  • 视频图像数据接入指南
  • STM32H743-ARM例程24-USB_MSC
  • asp网站防注入代码有源码搭建网站难不难
  • go语言每日3题
  • Mysql 坏表修复
  • 烟台专业网站建设湘潭网页设计
  • 网站按抓取手机软件贵阳wordpress 编程模式
  • Rust 结构体
  • 【2026计算机毕业设计】基于Springboot的微信小程序的古诗词在线学习系统
  • 基于微信小程序的运动康复中心预约系统的设计与实现(SpringBoot+Vue+Uniapp)
  • 微信小程序中使用 Vant Weapp 组件库
  • JAVA无人共享台球杆台球柜系统球杆柜租赁系统源码支持微信小程序
  • c 网站开发程序员网站建设 收费明细
  • dockerfile中CMD和ENTRYPOINT指令
  • 用服务器自建一套无界白板 + 文档协作平台 —— Affine
  • docker可视化面板portainer忘记密码的解决方案
  • Spring 4.1新特性:深度优化与生态整合
  • 湛江网站建设外包网站开发公司报价单模板
  • 画册设计公司网站优书网注册
  • 中国风手机网站模板html自动播放视频