如何通过数字索引访问Dictionary键,获取最后插入的对应键值?
解决方案
首先明确:C# 自带的普通Dictionary<TKey, TValue>本身不记录元素插入顺序,即便通过反射等非常规手段取到Keys集合的最后一个元素,也无法保证是最后插入的Key,无法满足你的需求。
下面给出两种可行实现方案:
方案1:使用.NET内置的泛型有序字典
如果你使用的是 .NET Core 2.0+ / .NET 5+ 及更高版本,可以直接用框架内置的 System.Collections.Generic.OrderedDictionary<TKey, TValue>,它原生支持按插入顺序存储元素,且Keys集合支持索引器访问:
using System.Collections.Generic; // 初始化有序字典 OrderedDictionary<string, int> myDict = new OrderedDictionary<string, int>(); myDict.Add("key1", 10); myDict.Add("key2", 20); myDict.Add("key3", 30); // 取最后插入的Key,注意索引从0开始,所以取Count-1的位置 string lastInsertedKey = myDict.Keys[myDict.Count - 1]; // 取对应值 int lastCount = myDict[lastInsertedKey];
方案2:自定义支持索引访问的有序字典
如果你使用的是旧版本.NET Framework,没有泛型有序字典可用,可以自己封装实现,同时维护字典存储和插入顺序列表:
public class IndexableOrderedDict<TKey, TValue> { private readonly Dictionary<TKey, TValue> _innerDict = new Dictionary<TKey, TValue>(); private readonly List<TKey> _insertOrder = new List<TKey>(); // 按键取值/赋值 public TValue this[TKey key] { get => _innerDict[key]; set { if (!_innerDict.ContainsKey(key)) { _insertOrder.Add(key); } _innerDict[key] = value; } } // 按插入顺序索引取Key public TKey this[int index] => _insertOrder[index]; public int Count => _innerDict.Count; public void Add(TKey key, TValue value) { _innerDict.Add(key, value); _insertOrder.Add(key); } public bool Remove(TKey key) { if (_innerDict.Remove(key)) { _insertOrder.Remove(key); return true; } return false; } // 可按需扩展Clear、ContainsKey等其他Dictionary原生方法 }
使用示例:
var myDict = new IndexableOrderedDict<string, int>(); myDict.Add("a", 1); myDict.Add("b", 2); // 取最后插入的Key string lastKey = myDict[myDict.Count - 1]; int lastCount = myDict[lastKey];
额外提醒:你原有代码的另一处错误是直接用
Count作为索引取值,所有C#集合的索引都是从0开始,最后一个元素的索引恒为Count - 1,直接用Count会触发索引越界异常。
内容的提问来源于stack exchange,提问作者MD. RAKIB HASAN
相关产品推荐
相关产品推荐

