C# 里的 KeyValuePair<TKey, TValue>
功能示例创建获取键pair.Key获取值pair.Value遍历字典构建集合转换成字典。
·
我们来详细讲讲 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.Generic | System.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;
}
}
}
仅供学习参考,如有侵权联系我删除。
更多推荐
所有评论(0)