Sorting Dictionary by Values

G

Guest

Hello,

I´ve a simple question about existing data structures/ collections.

Is there a way to sort a dictionary (or any comparable collection/ data
structure) by values instead of by keys?

For example if you have a dictionary with words as keys and the
frequency of these words in a text as values.

What is the most performant way to sort these dictionary by the
frequency of the words (=values)?



Regards,

Martin
 
B

Bill Block

Two options:

1) Use a List<T> impelementation to store your data objects, then use
the Sort() method. For example:

List<MyClass> m_list = new List<MyClass>();
m_list.Add(instance1);
m_list.Add(instance2);
m_list.Sort({Generic Comparison});

http://msdn2.microsoft.com/en-gb/library/w56d4y5z.aspx

2) Implement a custom sortable binding list implementation (if you need
binding as well). There is a good article on creating a
SortableBindingList in MSDN:


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnforms/html/winforms02182005.asp

Bill
 
J

John Timney \(MVP\)

oops - so it does.

Heres some code to sort the contents of the dictionary based on its values,
having key and vlaues both of type string. See if you can work with that.

Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "a Item");
s.Add("2", "c Item");
s.Add("3", "b Item");

List<KeyValuePair<string, string>> myList = new
List<KeyValuePair<string, string>>(s);
myList.Sort(
delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);

foreach (KeyValuePair<string, string> myKey in myList)
{
Response.Write(myKey.Key + " " + myKey.Value);
}


--
Regards

John Timney (MVP)
VISIT MY WEBSITE:
http://www.johntimney.com
http://www.johntimney.com/blog
 
T

Tony Gravagno

This article by Eric Gunnerson at Microsoft was very helpful for
creating a sorted, enumerable hash table:
http://tinyurl.com/yj2x8a
I made a minor tweak to the IterSortHashValue code to return an Object
which can be used like a Hashtable for DropDownLists which exposes
both a Key and a Value.

I haven't compared any of these techniques and don't know if the OP
really needs to have a Dictionary or if that's just what he happens to
be looking at, at the moment.

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top