Get the index of item in list based on value

可紊 提交于 2020-01-07 04:38:09

问题


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?


回答1:


 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;
 }



回答2:


What you could do is group the items based on the win percentage and goals (if both are the same, the teams will be in the same group), then apply the same position number to every element in the same group:

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

var positionGroups = this.results.GroupBy(x => new { WinPercentage = x.WinPercentage, Goals = x.Goals });
int position = 1;
foreach (var positionGroup in positionGroups)
{
    foreach (var team in positionGroup)
    {
        team.Position = position;
    }
    position++;
}



回答3:


The code below code will work for you

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


this.results.Foreach(x =>
{
    int index = this.results.FindIndex(y => y.Goals == x.Goals && y.WinPercentage == x.WinPercentage);
    x.Position = index > 0 ? this.results[index - 1].Position + 1 : 0;
});


来源:https://stackoverflow.com/questions/44202232/get-the-index-of-item-in-list-based-on-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!