Linq选择将为类似值生成关联分数

时间:2014-07-29 18:23:36

标签: c# .net linq select .net-4.5

我试图根据分数生成一个简单的排名表。

e.g。鉴于以下

List<Player> players = new List<Player>() {
    new Player { Name = "John", Score = 2 },
    new Player { Name = "Mary", Score = 1 },
    new Player { Name = "Bob", Score = 2 },
    new Player { Name = "Alice", Score = 3 },
};

var results = players
      .OrderByDescending(o => o.Score)
      .Select((v,i) => new { Name = v.Name, Score = v.Score, Position = i+1} );

结果将是。

Name  Score Pos
Alice 3     1 
John  2     2 
Bob   2     3 
Mary  1     4 

相反,我希望结果是

Name  Score Pos
Alice 3     1 
John  2     2 
Bob   2     2 <---- this guy is tied for second 
Mary  1     4 <---- this one still comes fourth

无论如何在Linq Select期间访问上一个或下一个元素,以便知道是否增加或减少索引值?

3 个答案:

答案 0 :(得分:5)

这样的事情可以帮到你吗?

  .Select((v,i) => new { Name = v.Name, 
                         Score = v.Score, 
                         Position = 
                            players.Count(p => p.Score > v.Score) + 1
                       }
         );

答案 1 :(得分:3)

但听起来你想通过/ selectmany做一个小组

      var results = players
              .OrderByDescending(o => o.Score)
              .GroupBy(o => o.Score)
              .SelectMany((l, i) => l.Select(v => new { Name = v.Name, Score = v.Score, Position = i + 1 }));

答案 2 :(得分:0)

您几乎拥有索引select语句的解决方案,但首先对数据集进行排序。

修改:进行了一次小编辑,因为我的分拣机排序错误,即按升序排序。

List<Player> players = new List<Player>() {
    new Player { Name = "John", Score = 2 },
    new Player { Name = "Mary", Score = 1 },
    new Player { Name = "Bob", Score = 2 },
    new Player { Name = "Alice", Score = 3 },
};

players.Sort(delegate(Player x, Player y)
{
    return y.Score.CompareTo(x.Score);
});

var results = players
      .Select((v,i) => new { 
        Name = v.Name, 
        Score = v.Score, 
        Position = i+1, 
        TiedWithPrevious = i > 0 && players[i-1].Score == v.Score, 
        TiedWithNext = i < players.Count-1 && players[i+1].Score == v.Score } );