根据值获取列表中项目的索引

Get the index of item in list based on value

该场景适用于足球联赛 table。我可以按比赛胜率对名单进行排序,然后按进球数来确定他们在联赛中的位置。然后,我使用此排序通过 IndexOf 函数获得球队在联赛中的位置 table。

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


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

当两支球队(应该是并列#1)的比赛胜率和进球数相同,但在获取索引时,一支球队将被分配为#1,另一支球队将被分配为#2,就会出现问题。

有没有办法得到正确的位置?

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

你可以做的是根据胜率和进球对项目进行分组(如果两者相同,则球队将在同一组),然后将相同的位置编号应用于同一组中的每个元素:

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

下面的代码对你有用

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

这是我的解决方案

  1. 定义一个class:
public class ABC
{
    public int A { get; set; }
    public int B { get; set; }
    public int R { get; set; }
}
  1. 构造数值:
List<ABC> list = new List<ABC>();
for (var i = 0; i < 100; i++)
{
    list.Add(new ABC()
    {
        A = i,
        B = i > 50 && i < 70 ? i + 20 : i + 1
    });
}
  1. 排序并打印值:
var result = list.OrderByDescending(d => d.B)
            .GroupBy(d => d.B)
            .SelectMany((g, `i`) => g.Select(e => new ABC()
            {
                A = e.A,
                B = e.B,
                R = i + 1
            })).ToList();

foreach (var t in result)
{
   Console.WriteLine(JsonConvert.SerializeObject(t));
}
Console.ReadLine();
  1. 结果: