DAVEWASLIN
DAVEWASLIN

Reputation: 159

Linq order list using list property

If i have a list of football teams, and each team contains a list matches. If each match has a property of goals scored, how can i order the list of football teams so that it is ordered by the most goals scored in the lastest match, followed by the match before and so on? The number of matches is unknown.

I cant figure out the linq and im not having much luck with investigating dynamic linq

Many thanks

The number of matches will always be the same and theoretically there isnt a maximum although it is reasonable to expect that it will be less than 20. If the number of goals is the same it will use team name in alphabetical order.

Upvotes: 1

Views: 120

Answers (2)

recursive
recursive

Reputation: 86164

Recursion seems to not be necessary. Here's an iterative approach.

void Main() {
    var teams = CreateTeams().ToArray();
    int games = teams.Min(t => t.Games.Count);
    var ordered = teams.OrderBy(team => 0);

    for (int i = games - 1; i >= 0; i--) {
        var captured = i; // the value of i will change, so use this capturing variable, 
        ordered = ordered.ThenByDescending(team => team.Games[captured].Points);
    }
    ordered = ordered.ThenBy(team => team.Name);

    foreach (var team in ordered) {
        Console.WriteLine("{0} {1}", team.Name, string.Join(", ", team.Games.Select(game => game.Points)));
    }
}

IEnumerable<Team> CreateTeams() { 
    yield return (new Team("War Donkeys", 1, 2, 3));
    yield return (new Team("Fighting Beavers", 2, 2, 3));
    yield return (new Team("Angry Potatoes", 2, 1, 3));
    yield return (new Team("Wispy Waterfalls", 3, 2, 1));
    yield return (new Team("Frisky Felines", 1, 2, 3));
}

class Team {
    public string Name { get; set; }
    public IList<Game> Games { get; set; }

    public Team(string name, params int[] points) {
        this.Name = name;
        this.Games = points.Select(p => new Game { Points = p }).ToArray();
    }
}

class Game {
    public int Points { get; set; }
}

The output is

Fighting Beavers 2, 2, 3
Frisky Felines 1, 2, 3
War Donkeys 1, 2, 3
Angry Potatoes 2, 1, 3
Wispy Waterfalls 3, 2, 1

Upvotes: 1

D Stanley
D Stanley

Reputation: 152634

Linq doesn't do recursion natively. You may need to define a custom comparer in order to to the recursive search, then pass that to OrderBy. Without seeing the actual structure the pseudo-code would be:

N = 1
while(true)
{
   if L has less than N matches
       if R has less than matches
           return L.Name.CompareTo(R.Name)  // order by team name
       else
           return 1 // R has more matches

   if R has less than matches // L has more matches
        return -1

   compare Nth match of each team
   if equal
       N = N + 1; 
   else
       return compare result
}

Upvotes: 1

Related Questions