对Dictionary<TKey,TValue>进行插入与替换操作

 Dictionary<string, int> Lengths = new Dictionary<string, int>();
            for (int n = 0; n < tableArray.Length - 1; n++)
            {
                for (int u = 0; u < tableLengths.Count; u++)
                {
                    if (tableLengths[u].Name == tableArray[n])
                    {
                        Lengths.Add(tableLengths[u].Name, tableLengths[u].Length);//添加查询使用的表到数据字典
                    }
                }
            }
            var list = (from d in Lengths orderby d.Value ascending select d).ToList();//对数据字典进行排序
            for (var i = 0; i < list.Count; i++)
            {
                switch (list[i].Key)
                {
                    case "Test":

                        list.Insert(i, new KeyValuePair<string, int>("you want to insert codes", list[i].Value));//在当前位置插入新的元素,注意这边的类型为KeyValuePair
                       //如果当前i值为0,则插入的新元素索引即为0 
                       //原来索引为0的变为1,以下的元素索引都自动加1

                        // list.RemoveAt(i + 1);//如果要删除原索引的元素,则i要加1,添加该部则完成替换操作
                        break;
                    default:
                        break;
                }

            }

注: C#中还有一个Replace方法,用法为:var a= list[i].Key.Replace("Test", "aa");
如果list[i].Key值为Test则a返回值aa,原字典序列中元素不变。

原文地址:https://www.cnblogs.com/QiuJL/p/4524220.html