Sorting a generic list

Published Sunday, December 16, 2007 By Steven Stewart

Recently I needed to sort a generic list, I've always pretty much populated a generic list in the order I expect the output.  This time though the order could change after I had retrieved the data and populated the generic list.

So, for example lets take look at a leader board.  Below is a class that represents the position, score etc in a tournament.

public class TournamentStanding
{
    private int _postion;
    private int _score;
    private string _prize;
    private string _playerName;
    private DateTime _datePlayed;

    public int Position
    {
        get { return _postion; }
        set { _postion = value; }
    }
    public int Score
    {
        get { return _score; }
        set { _score = value; }
    }
    public string Prize
    {
        get { return _prize; }
        set { _prize = value; }
    }
    public string PlayerName
    {
        get { return _playerName; }
        set { _playerName = value; }
    }
    public DateTime DatePlayed
    {
        get { return _datePlayed; }
        set { _datePlayed = value; }
    }
}

 

So lets create a generic list containing two players.

List<TournamentStanding> standings = new List<TournamentStanding>();
TournamentStanding player1 = new TournamentStanding();
TournamentStanding player2 = new TournamentStanding();

// Populate player1 & player2

standings.Add(player1);
standings.Add(player2);

 

Ok so now we want to sort on Position.  Well it's pretty easy we just need to use a delegate and the CompreTo method.  Pretty easy eh!

standings.Sort(delegate(TournamentStanding t1, TournamentStanding t2) { return t1.Position.CompareTo(t2.Position); });