• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 759
  • Last Modified:

How to sort C# dictionary

asp.net 2.0, c#.  I select data from the SQL Database, and then populate it in a dictionary...

  Dictionary<string, int> dQuotes = new Dictionary<string, int>();

          if (dQuotes.ContainsKey(dr["Quotation"].ToString()))
            dQuotes[dr["Quotation"].ToString()] = dQuotes[dr["Quotation"].ToString()] + 1;
            dQuotes.Add(dr["Quotation"].ToString(), 1);

I then create a Goole Chart URL using the dictionary...
        foreach (KeyValuePair<string, int> pair in dQuotes)
          txtQuotes.Text += i1.ToString() + "      " + pair.Value + "    " + pair.Key + "\r\n";
          if (i1 > 0) //so that there is not an ',' at the end
            strQuoteChd += ",";
          strQuoteChd += pair.Value; //Data
          strQuoteChxl += "|" + pair.Value;  //Bottom text
          //strQuoteChdl += "|" + pair.Key;  //Bottom text
          strQuoteTopText += "|" + pair.Value;

The problem with this is that i want to display the chart in a sorted order by value (right now it comes out in the order of the key).  How to do this, do I need to use so kind of sorted collection (I cannot use Linq, it is a asp.net 2.0 website).  Please give the complete code.
1 Solution
You can use something like this:

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);
    delegate(KeyValuePair<string, stringfirstPair>,
    KeyValuePair<string, stringnextPair>)
        return firstPair.Value.CompareTo(nextPair.Value);

Or you can implement a IComparer see

If you'll use simple List<string> then it will behave like your dictionary sorted by value (which is incremental and nothing but insertion order).
eelouAuthor Commented:
cadsjo:  Did you note that my existing dictionary is string,int?  when I do this...
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(dQuotes);

I get...
Overload argument has some invalid arguments

If I change it to the following, that error goes away
List<KeyValuePair<string, intg>> myList = new List<KeyValuePair<string, int>>(dQuotes);

In either case I still have errors starting with the delegate statement, multiple errors.


Lazyberezovsky:  I asked for specific code, not to be pointed to something
Todd GerbertIT ConsultantCommented:
This seems a little bit sloppy to me, but it's all that comes to mind.
Copy all the key/value pairs to a List<KeyValuePair<string, int>>, sort the list, clear the dictionary, add the elements of the sorted list back to the dictionary.

private static void SortDictionaryByValue(Dictionary<string, int> dictionary)
	List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();

	foreach (KeyValuePair<string, int> kvp in dictionary)
	list.Sort(new Comparison<KeyValuePair<string, int>>(delegate(KeyValuePair<string, int> a, KeyValuePair<string, int> b)
		if (a.Value < b.Value)
			return -1;
		else if (a.Value > b.Value)
			return 1;
			return 0;

	foreach (KeyValuePair<string, int> kvp in list)
		dictionary.Add(kvp.Key, kvp.Value);

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now