Saturday, November 15, 2008

Sorting Dictionary object in .Net

A few days ago I came across a sorting-dictionary problem at work. The easiest way to have a sorted dictionary in .Net is to use the SortedDictionary(TKey, TValue) item. Every time you enter a keyvaluepair in the SortedDictionary item, it will be sorted automatically.

But I had to sort an existing Dictionary(TKey, TValue) item, that was provided by some other program. Initially, I was hoping that there is some Dictionary.Sort() function available that I could use but there isn't.

After some research I found that you could use the List.Sort() function to sort the dictionary by keys. But that is not all. You also need to add a delegate in the List.Sort() function to carry out the sorting process.

Here is the code.

//Code takes a Dictionary<double,int> item, sorts it and return the new Dictionary<double,int> item

private static Dictionary<double,int> Sort(Dictionary<double,int> Dict)
{
//Create a List object from the Dictionary item
List<keyvaluepair<double,int>> result = new List<keyvaluepair<double,int>>(Dict);


//Use the delegate in the List.Sort function to compare the keys for sorting
result.Sort(
delegate(
KeyValuePair<double, int> first,
KeyValuePair<double, int> second)
{
return first.Key.CompareTo(second.Key);
}
);

//Add the List items into a new dictionary item
Dictionary<double,int> sortedDict = new Dictionary<double,int>();

foreach (KeyValuePair<double, int> kvp in result)
{

double key = kvp.Key;
int value = kvp.Value;

sortedDict.Add(key, value);
}

return sortedDict;
}



If there is a better way to achieve this, please let me know.

17 comments:

Anonymous said...

Hi! I came across this randomly, but...

I believe you can just create a new SortedDictionary instance and pass in the original dictionary in the constructor, i.e.:

Dictionary<string,int> dict = new Dictonary<string, int>; // as the existing entry

SortedDictionary<string, int> sortedDict = new SortedDictionary<string, int>(dict); // now it's sorted

anyways, you get the idea. Maybe not any faster (?), but definitely easier to think about. :)

Syed Rizvi said...

Hi Anonymous!
Your suggested method is definitely more easier to think and to remember. Thanks for sharing it.

Anonymous said...

I apologise, but, in my opinion, you are not right. Write to me in PM, we will discuss.

Anonymous said...


bookmarked!!, I really like your web site!

Anonymous said...

Јust go through the internеt аnԁ dіscover
the best source to get all these humоrous images.

That is why we have ԁedicateԁ thiѕ pagе to help you reneω your spirit аnԁ pеrhaрs haѵе a few lаughs too.

We are offering the latest nеws updаteѕ about youг famous celebritіes.


Feel free to surf to my blog post ... christmas funny pictures and cartoons

Anonymous said...

It іmproves blood and oxygеn flow tο the muscles that are recovering from the pгіor haгԁ wοrkout.

Eνеn if your ѕmall business doeѕn't have some sort of refrigerator (a rarity today) you can choose vegetable and fruit that do not even require refrigeration. Get your heart rate up with a quick burst of fast movement.

My website: http://www.veteranjournal.com

Anonymous said...

Take а loоκ аt your sсhedule аnd come оf ωith
solutionѕ aheaԁ οf tіme for lunchеѕ
and dinneгs оut, this wіll givе уou a game plan tο follow.
It is important that уοu realise
thаt if yοu dо mіѕs one of уouг exеrcise sеsѕions it is
not thе еnd of the wоrld.
Take note alѕo that yοu κnow how to ρerfoгm the еxеrcise well to аvoіd ѕiсknеss and injuriеѕ in the futurе.


Review mу blog post - fun fitness tips and facts

Anonymous said...

What's up, how are things? I just mentioned this information along with a colleague, we had a healthy snicker.

My web site: simply click the up coming internet site

Anonymous said...

choοse numerous softwаres that are
cаpable enοugh to satisfy yοuг necеssitіes.
Тhe goаl with a funnу pіcture іs tо have the photοgraph be аlmоst a blank cаnvas
for you to put thе punch line οn.

Μany of the ρaintings have a tendеnсy to use
a sіgnaturе in оrder tο improve a funny meѕsagе
that's shown in the photo.

Stop by my web blog - http://www.facebook.com/pages/LoLz-Paradise/510406835655540
Also see my webpage: ontheqtease.com

Anonymous said...

I usually do not comment, hoωeveг after rеading through а lot
of commеnts on this ρаge "Sorting Dictionary object in .Net".
I do have 2 questions foг you if it's okay. Could it be only me or does it appear like a few of the comments come across like they are left by brain dead individuals? :-P And, if you are writing on other sites, I'd liκe to follow you.
Would уou make a list of the cоmplete
urlѕ of all yοuг public ρages lіke your
linkedin prоfile, Faсeboоκ page or twitter feed?


Visit mу webѕite; home Page

Anonymous said...

They aim at miming various good qualities of the counterparts of the
assumed celebrity. Both the content and presentation of news are drastically different from what it used to be.
I want to mention a part of the Prime Law (Twelve Visions Party) which is part of Neothink.


Also visit my site ... Latest Daily News

Anonymous said...

Of course, one of the reasons why this area of Ohio has remained
so persistently branded as a pocket of joblessness is its failure to recover from
the death of the steel industry and also because of automotive production lines outsourced to
foreign lands. He tells the tale of a young boy, a tot, who was
riding a toy car near the railroad crossing.
On you left you will notice list of content providers and on the right is the advanced search option where you can search
video clips by typing in the exact phrase (in quotes), or at least
one of the keywords to narrow down your search.

Here is my webpage: http://bharatjanani.com/groups/rapid-programs-of-world-news-uncovered/

Anonymous said...

Your payments will not only get to you faster but it will provide
you with a history of your earnings for your records.
' The picture is just as worrying for youngsters - by 2010, it's predicted 22 per cent of girls and 19 per
cent of boys between the ages of two and 15 will be obese,
with girls under 11 at particular risk. What I tell my clients
is that they need to schedule their fitness time like it's a doctor's appointment.


Feel free to surf to my blog post: Highly recommended Internet site

Anonymous said...

This study shows that progression of AIDS become rapid in the presence
of negativity due to less social gathering and stress in life.
But my favorite is the link that tells you about bad dates stories,
of course they are the funniest. We are offering the latest
news updates about your famous celebrities.

My web-site - funny pictures and quotes for facebook

Anonymous said...

I believe that each of us has the potential to create personal
miracles, and to spread these miracles throughout the world.

The ultimate online news source that covers news,
travel, money, sports, life, technology and weather.
They can also update news on their site as and when the event occurs while
the newspapers have to wait until the next morning.


My web-site Latest Daily News

Anonymous said...

Your way of describing everything in this post is truly fastidious, every one be capable
of effortlessly know it, Thanks a lot.

my blog: mouse click the up coming article

oakleyses said...

true religion jeans, ray ban pas cher, michael kors, oakley pas cher, polo lacoste, michael kors outlet online, ray ban uk, mulberry uk, michael kors outlet online, coach outlet, burberry handbags, nike air force, vans pas cher, true religion outlet, michael kors outlet, abercrombie and fitch uk, nike roshe run uk, replica handbags, burberry outlet, michael kors outlet online, kate spade, hollister pas cher, michael kors outlet online, sac hermes, nike air max uk, true religion outlet, nike air max uk, michael kors outlet, guess pas cher, north face, hollister uk, new balance, nike tn, uggs outlet, uggs outlet, ralph lauren uk, michael kors, true religion outlet, nike air max, timberland pas cher, nike blazer pas cher, sac vanessa bruno, converse pas cher, coach purses, coach outlet store online, north face uk, nike free uk, hogan outlet, michael kors outlet