Linq Select将为相似的值生成并列分数
本文关键字:Select 相似 Linq | 更新日期: 2023-09-27 18:15:33
我正在尝试生成一个基于分数的位置数字的简单联赛表。
。给定以下
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中是否有访问上一个或下一个元素的方法,以便您知道是增加还是减少索引值?
像这样的东西会对你有用吗?
.Select((v,i) => new { Name = v.Name,
Score = v.Score,
Position =
players.Count(p => p.Score > v.Score) + 1
}
);
它听起来像你想做一个组by/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 }));
您几乎有了索引选择语句的解决方案,但首先对数据集进行排序。
Edit:做了一个小的编辑,因为我把排序器的顺序搞错了,即它是按升序排序的。
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 } );