Link to home
Start Free TrialLog in
Avatar of eelou
eelou

asked on

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;
          }
          else
          {
            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 += ",";
          }
          i1++;
          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.
Avatar of cadsjo
cadsjo
Flag of Netherlands image

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

Or you can implement a IComparer see
http://stackoverflow.com/questions/931891/sorted-dictionary-in-c

Cadsjo
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).
Avatar of eelou
eelou

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial