zoukankan      html  css  js  c++  java
  • 对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,原字典序列中元素不变。

  • 相关阅读:
    10.23继承
    10.22语法 class 类 面向对象概念 类与对象 对象的使用 绑定方法
    10.18
    10.16
    读书笔记-软技能:代码之外的生存指南
    git reset
    阿里云安装samba
    关于svn由于目标计算机积极拒绝,无法连接的解决办法
    yii2简单安装
    指定路径创建中文文件名并存入内容
  • 原文地址:https://www.cnblogs.com/QiuJL/p/4524220.html
Copyright © 2011-2022 走看看