Click here to Skip to main content
15,922,325 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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
Posted

Here at CodeProject there is an article about: "OrderedDictionary<t>: A generic implementation of IOrderedDictionary"[^]
 
Share this answer
 
Comments
Wendelius 23-Mar-11 16:49pm    
Good link, +5.
elad2109 23-Mar-11 16:53pm    
I saw this before. I prefer .net type. If I find no such I might use that. Thanks
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;
 
Share this answer
 
Comments
elad2109 23-Mar-11 16:51pm    
My Values don't have any oridinal or comparer.

1) Generally - How do I implement it?

2) Specific - I want to oreder the Values by thier "Percent" field (decimal value). Is there any "clean" syntax to do so ?
elad2109 23-Mar-11 16:54pm    
Can I write:

"order by item.Value.percent"

?
elad2109 24-Mar-11 15:20pm    
BTW, how can I define and how do I use a comperator obj in c# (like in java)?
How can I apply LINQ to object to oreder according to that comperator?
Wendelius 24-Mar-11 15:43pm    
Don't know Java enough but perhaps these examples would help:
http://msdn.microsoft.com/en-us/vcsharp/aa336756
elad2109 24-Mar-11 17:39pm    
Exactly what I was looking 4. 10x !
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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900