Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sort List by multiple conditions

Tags:

c#

sorting

I need to sort some soccer standings. My problem is how to sort in the right order.

Sortorder:

  • Points DESC
  • Approximation match
  • Goal difference DESC
  • Goals scored DESC
  • Goals against

Input: TeamName - Points - GoalsScored - GoalsAgainst

  • Team 1 - 1 - 4 - 7
  • Team 2 - 5 - 8 - 6
  • Team 3 - 1 - 2 - 10
  • Team 4 - 8 - 12 - 5
  • Team 5 - 5 - 7 - 4

... Match #4 - Team 5 - Team 2 -- 1-2

Match #7 - Team 1 - Team 3 -- 3-3 ...

Output: TeamName - Points - GoalsScored - GoalsAgainst

  • Team 4 - 8 - 12 - 5
  • Team 2 - 5 - 8 - 6
  • Team 5 - 5 - 7 - 4
  • Team 1 - 1 - 4 - 7
  • Team 3 - 1 - 2 - 10

Because Team 2 won over Team 5 they ends up at 2nd place.

Because Team 1 draw against Team 3, they ends up at 4. place, with a better goal difference.

public class Standing
{
    public Team Team { get; set; }
    public int? MatchesPlayed { get; set; }
    public int? GoalsScored { get; set; }
    public int? GoalsAgainst { get; set; }
    public int? Points { get; set; }
}

public class Match
{
    public int MatchID { get; set; }
    public DateTime? PlayTime { get; set; }
    public Team HomeTeam { get; set; }
    public Team AwayTeam { get; set; }
    public int? HomeScore { get; set; }
    public int? AwayScore { get; set; }
}

public class Pool
{
    public int PoolID { get; set; }
    public string PoolName { get; set; }
    public DateTime? StartTime { get; set; }
    public List<Team> Teams { get; set; }
    public List<Match> Matches { get; set; }
    public List<Standing> Standings { get; set; }
}
like image 224
Frets Avatar asked Nov 30 '25 12:11

Frets


2 Answers

Can you use .NET 3.5? It's pretty straightforward to use the LINQ OrderBy and ThenBy extension methods for this.

like image 81
Tim Robinson Avatar answered Dec 02 '25 01:12

Tim Robinson


I think you should check out the IComparable interface and consider implementing it over your object(s).

like image 27
No Refunds No Returns Avatar answered Dec 02 '25 01:12

No Refunds No Returns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!