Search code examples
c#linqindexof

Get the index of item in list based on value


The scenario is for a football league table. I can order the list by match win percentage and then by goals scored to determine their position in the league. I then use this ordering to get teams position in the league table using the IndexOf function.

this.results = this.results.OrderByDescending(x => x.WinPercentage).ThenByDescending(x => x.Goals);


this.results.Foreach(x => x.Position = this.results.IndexOf(x));

The problem arises when two teams (should be joint #1) have the same match win percentage and goals scored but when getting the index one team will be assigned #1 and the other #2.

Is there a way to get the correct position?


Solution

  •  var position = 1;
     var last = result.First();
     foreach(var team in results)
     {
         if (team.WinPercentage != last.WinPercentage || team.Goals != last.Goals)
            ++position;
    
         team.Position = position;
         last = team;
     }