C# 替换字典的键或值
因为ElementAt(index)方法是只读的,不能改动键或值,需要通过ToDictionary方法
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass
{
public static void Main()
{
Dictionary<string, int> testDict = new Dictionary<string, int>();
testDict.Add("k1", 1);
testDict.Add("k2", 2);
testDict.Add("k3", 3);
Console.WriteLine("替换前:" + testDict.ElementAt(0).Key); //替换前:k1
//将testDict的第一个键k1修改为看k10
testDict = testDict.ToDictionary(k => k.Key == "k1" ? "k10" : k.Key, k => k.Value);
Console.WriteLine("替换后:" + testDict.ElementAt(0).Key); //替换后:k10
}
}
摘自:https://blog.csdn.net/LLLLL__/article/details/108727607