Sorting a List of Dictionaries in C#?

Help!

I am new to C# and have spent all day trying to work out a way to do the following.

Read a XML file that contains a player’s name and player’s score and store it in a variable. I have been using a Dictionary.

Place all these dictionaries into a List.

Sort the list of dictionaries by the high score. (can’t work this out)

Have the ability to add another new score and sort again.

Write the results back to the file I loaded it from.

Is the approach I’m taking wrong using a List of Dictionaries? Any advice would be a great help.

Thanks.

using System.Linq;

 var sortedList = myListOfDictionaries.OrderBy(d=>d["yourScoreName"]).ToList();

Starting C# by sorting a list of dictionary seems a bit bold, but anyway :

You need to use the Sort function. You need a function to compare two dictionary (I will assume it’s a <string, int> dictionary) :

private static int CompareDictionariesByScore (Dictionary<string, int> x,
                                            Dictionary<string, int> y)
{
    if (x == null)
    {
        if (y == null)
        {
            // If x is null and y is null, they're
            // equal. 
            return 0;
        }
        else
        {
            // If x is null and y is not null, y
            // is greater. 
            return -1;
        }
    }
    else
    {
        // If x is not null...
        //
        if (y == null)
            // ...and y is null, x is greater.
        {
            return 1;
        }
        else
        {
            // ...and y is not null, compare the 
            // lengths of the two dictionaries.
            int xScore = x[ "Score" ];
            int yScore = y[ "Score" ];

            if( xScore == yScore ) return 0;
            else if( xScore > yScore ) return 1;
            else return -1;
        }
    }
}

Then, you can sort the list that way

list.Sort( CompareDictionariesByScore );

Why not use a SortedDictionary<> instead?

Also, there’s about a gazillion useful google hits for that:

Thanks for all the suggestions - in the end I simplified it. Dictionaries were overkill and I created a value object to store the players name and score. I then used OrderBy that was mentioned in an answer above to order on one of the vo properties.