对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/archive/2012/05/17/4524220.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值