c# – 在特定位置添加字典元素
发布时间:2020-12-15 19:50:31 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: var myDict = new Dictionarystring,int();myDict.Add("Key1",1);myDict.Add("Key2",2);myDict.Add("Key4",4);myDict.Add("Key5",5);foreach (KeyValuePairstring,int pair in myDict){ Console.Write(pair.Key + @" -- "); Console.WriteL
请考虑以下代码:
var myDict = new Dictionary<string,int>(); myDict.Add("Key1",1); myDict.Add("Key2",2); myDict.Add("Key4",4); myDict.Add("Key5",5); foreach (KeyValuePair<string,int> pair in myDict) { Console.Write(pair.Key + @" --> "); Console.WriteLine(pair.Value); } myDict.Add("Key3",3); foreach (KeyValuePair<string,int> pair in myDict) { Console.Write(pair.Key + @" --> "); Console.WriteLine(pair.Value); } 我想要做的是在“Key2”和“Key4”之间插入“Key3”.为简单起见,我以此为例.我知道我可以使用SortedDictionary,我可以让这个例子起作用.我需要能够具体做的是,每当我在字典中插入一个新元素时,我总是希望它在第二个元素之后和第三个元素之前插入它.我怎么能做到这一点? 解决方法
您可以使用
OrderedDictionary .
OrderedDictionary.Insert 允许您指定要插入密钥的索引.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |