当前位置: 首页 > 编程语言 > C#

通用键-值对集合保留插入顺序?分享

时间:2023-04-11 00:12:32 C#

键/值对的通用集合保留插入顺序?我正在寻找类似字典但保证保留插入顺序的东西。由于Dictionary是一个哈希表,我认为它不是。是否有通用集合,或者我是否需要使用旧的.NET1.1集合之一?那没有。但是,System.Collections.Specialized.OrderedDictionary应该可以满足您的大部分需求。编辑:另一种选择是使其通用。我还没有测试过它,但它编译(C#6)并且应该可以工作。但是,它仍然具有与下面评论中提到的OndrejPetrzilka相同的限制。公共类OrderdDictionary{公共OrderedDictionaryUnderlyingCollection{得到;}=新的OrderedDictionary();publicKthis[Tkey]{get{return(K)UnderlyingCollection[key];}set{UnderlyingCollection[key]=value;}}publicKthis[intindex]{get{return(K)UnderlyingCollection[index];}set{UnderlyingCollection[index]=value;}}publicICollectionKeys=>UnderlyingCollection.Keys.OfType().ToList();公共ICollection值=>UnderlyingCollection.Values.OfType().ToList();publicboolIsReadOnly=>UnderlyingCollection.IsReadOnly;publicintCount=>UnderlyingCollection.Count;publicIDictionaryEnumeratorGetEnumerator()=>UnderlyingCollection.GetEnumerator();publicvoidInsert(intindex,Tkey,Kvalue)=>UnderlyingCollection.Insert(index,key,value);publicvoidRemoveAt(intindex)=>UnderlyingCollection.RemoveAt(index);publicboolContains(Tkey)=>UnderlyingCollection.Contains(key);publicvoidAdd(Tkey,Kvalue)=>UnderlyingCollection.Add(key,value);publicvoidClear()=>UnderlyingCollection.Clear();publicvoidRemove(Tkey)=>UnderlyingCollection.Remove(key);publicvoidCopyTo(Arrayarray,intindex)=>UnderlyingCollection.CopyTo(array,index);实际上有一个,它是通用的,自.net2.0以来就存在,它称为KeyedCollection。但是,它具有从值构造键的局限性,因此它不是键/值对的一般集合。如果您需要它作为IDictionary,它有一个.Dictionary属性。我遇到的一个小问题是它是一个抽象类,你必须将它子类化并实现:protectedabstractTKeyGetKeyForItem(TItemitem)虚拟方法比lambda快一点(对此有任何评论)。有一个OrderedDictionary类,它是一个字典,但可以按插入顺序进行索引,但它不是通用的。目前在.Net框架中没有一个通用的。我从.Net团队的某个人那里读到一条评论,他们可能会在未来实现一个通用版本,但如果是这样,它很可能被称为IndexableDictionary而不是OrderedDictionary以使其行为更加明显。编辑:找到报价。它出现在OrderedDictionary的MSDN页面上,归功于Microsoft的DavidM.Kean:类型实际上是错误的;它不是“有序”字典,而是“索引”字典。尽管目前还没有这种类型的等效通用版本,但如果我们将来添加一个,我们可能会将该类型命名为“IndexedDictionary”。好吧,您可以使用List>,这将保留顺序...但是您将失去字典的查找功能。为什么我需要保留订单?代码项目有一个通用的实现和合理数量的测试用例。作者取了一个比较搞笑的名字(KeyedList),让人不好找。这是非泛型Systems.Collections.Specialized.OrderedDictionary类型的包装器。此类型将按插入顺序返回一系列键/值/对,很像Ruby2.0哈希。它不需要C#6魔法,符合IDictionary(这也意味着访问未分配的键会引发异常),并且应该是可序列化的。对Adrian的回答的每条评论都将其命名为“IndexedDictionary”。它因人而异。使用系统;使用系统集合;使用System.Collections.Generic;使用System.Collections.Specialized;使用System.Linq;//////维护键插入顺序的字典。//////这对于发出JSON很有用,在这种情况下,出于各种更人性化的原因,最好保持键顺序///。//////在不使用键/值或枚举器(例如)的情况下,不支持手动重新排序键或通过索引访问键///。///[Serializable]publicsealedclassIndexedDictionary:IDictionary{//仅在.NET4.5中的非泛型版本privatereadonlyOrderedDictionary_backing=newOrderedDictionary();privateIEnumerable>KeyValuePairs{get{return_backing.OfType().Select(e=>newKeyValuePair((TKey)e.Key,(TValue)e.Value));}}publicIEnumerator>GetEnumerator(){返回KeyValuePairs.GetEnumerator();}IEnumeratorIEnumerable.GetEnumerator(){返回GetEnumerator();}publicvoidAdd(KeyValuePair它em){_backing[item.Key]=item.Value;}publicvoidClear(){_backing.Clear();}publicboolContains(KeyValuePairitem){return_backing.Contains(item.Key);}publicvoidCopyTo(KeyValuePair[]array,intarrayIndex){KeyValuePairs.ToList().CopyTo(array,arrayIndex);}publicboolRemove(KeyValuePairitem){TValue值;如果(TryGetValue(item.Key,outvalue)&&Equals(value,item.Value)){Remove(item.Key);返回真;}返回假;}publicintCount{get{return_backing.Count;}}publicboolIsReadOnly{get{return_backing.IsReadOnly;}}publicboolContainsKey(TKeykey){return_backing.Contains(key);}publicvoidAdd(TKeykey,TValuevalue){_backing.Add(key,value);}publicboolRemove(TKeykey){varresult=_backing.Contains(key);如果(结果){_backing.Remove(键);}返回结果;}publicboolTryGetValue(TKeykey,outTValuevalue){objectfoundValue;如果((foundValue=_backing[key])!=null||_backing.Contains(key)){//要么找到一个非空值,要么包含的值为空。值=(TValue)foundValue;返回真;}值=默认值(TValue);返回假;}publicTValuethis[TKeykey]{get{TValue值;if(TryGetValue(key,outvalue))返回值;抛出新的KeyNotFoundException();}set{_backing[key]=value;}}publicICollectionKeys{get{return_backing.Keys.OfType().ToList();}}publicICollectionValues{get{return_backing.Values.OfType().ToList();我知道你在写C#,但是Java有一个叫做LinkedHashMap的类,它使用一个私有的LinkedList来维护键的插入顺序如果你找不到合适的通用解决方案,这可能是你的开始实现你自己的。保持插入的通用键/值对的另一种选择是使用类似的东西:Queue>这将是一个有保证的有序列表。除了调整数组大小,您还可以按类似于添加/删除字典的顺序对队列进行入队和出队。它通常可以充当非调整大小排序(通过插入)数组和自动调整大小无序(通过插入)列表之间的中间地带。如果您需要Add、Remove、ContainsKey和顺序保存的恒定复杂性,.NETFramework4.5中没有此类泛型。如果您对第三方代码没问题,请查看我的存储库(许可的MIT许可证):https://github.com/OndrejPetrzilka/Rock.Collections有一个OrderedDictionary集合:代码://ASortedDictionary排序在键(不是值)System.Collections.Generic.SortedDictionarytestSortDic=newSortedDictionary();//添加一些key乱序的valuestestSortDic.Add("key5","value1");testSortDic.Add("key3","value2");testSortDic.Add("key2","value3");testSortDic.Add("key4","value4");testSortDic.Add("key1","value5");//显示元素。foreach(KeyValuePairkvpintestSortDic){Console.WriteLine("Key={0},value={1}",kvp.Key,kvp.Value);}输出:以上是C#学习教程:Genericcollectionofkey/valuepairspreservesinsertionorder?分享的所有内容,如果对你有用,需要进一步了解C#学习教程,希望大家多多关注——Key=key1,value=value5Key=key2,value=value3Key=key3,value=value2Key=key4,value=value4Key=key5,value=value1本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: