是否有类型安全的有序字典替代项? [英] Is there a type-safe ordered dictionary alternative ?

查看:67
本文介绍了是否有类型安全的有序字典替代项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字典中保存一些对.
最后,我想将字典序列化为JSON对象.
然后,我打印Json.我希望成对的印刷顺序与输入字典的顺序相同.

起初,我使用一本普通的字典.但是后来我认为顺序可能不会保留.
然后我迁移到OrderedDictionary,但不使用Generic,这意味着它不是类型安全的.

您对我还有其他好的做法解决方案吗?

感谢

I want to save some pairs in a dictionary.
At the end I want to serialize the dictionary to JSON object.
i then print the Json. I want the pairs to be printed in the same order they were entered to the dictionary.

At first I used an ordinary dictionary. But then I thought the order might not be kept.
Then I migrated to OrderedDictionary but doesn''t use Generic, meaning it''s not typed-safe.

Do you have any other good-practice solution for me?

Thanks

推荐答案

在CodeProject上有一篇有关以下内容的文章:"OrderedDictionary< t>:IOrderedDictionary的通用实现" [
Here at CodeProject there is an article about: "OrderedDictionary<t>: A generic implementation of IOrderedDictionary"[^]


有关SortedDictionary的信息: http://msdn.microsoft.com/en-us/library/f7fta44c.aspx [ ^ ].

另一方面,如果您的类的实例包含序数,则基本上可以使用任何泛型集合,并且在序列化之前,可以使用LINQ按排序顺序将项目拉出,例如(取决于集合类型):
What about SortedDictionary: http://msdn.microsoft.com/en-us/library/f7fta44c.aspx[^].

On the other hand if the instance of your class contains the ordinal, you could use basically any generic collection and before serializing pull out the items in sorted order for example using LINQ, something like (depending on the collection type):
var orderedlist = from item in myDict
                  order by item.Ordinal
                  select item;


如果您的键/值没有排序,我认为您需要的是最常用的泛型类System.Collections.Generic.Dictionary<TKey, TValue>.我也认为您永远不需要过时的非通用集合.

—SA
If your key/values are not ordered, I think what you need is the most used generic class System.Collections.Generic.Dictionary<TKey, TValue>. I also think you never need obsolete none-generic collections.

—SA


这篇关于是否有类型安全的有序字典替代项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆