我正在尝试实现排名功能,如下所示:
Name Points rank
ram 9 1
kamal 9 1
preet 8 2
lucky 7 3
kishan 6.5 4
devansh 6 5
neha 6 5
我使用下面的代码来实现这个目标:
finalResult = finalResult.OrderByDescending(i => i.points).ThenBy(i => i.academy).ToList();
finalResult = finalResult.AsEnumerable() // Client-side from here on
.Select((player, index) => new RankingEntity()
{
competitorid = player.competitorid,
firstname = player.firstname,
lastname = player.lastname,
academy = player.academy,
points = player.points,
place = player.place,
eventId = player.eventId,
eventname = player.eventname,
categoryname = player.categoryname,
Rank = index + 1
}).ToList();
var t = (from i in finalResult
let rank = finalResult.First(x => x.points == i.points)
select new
{
Col1 = i,
Rank = rank.Rank
}).ToList();
List<RankingEntity> ttt = new List<RankingEntity>();
foreach (var item in t)
{
var a = item.Col1;
var row = new RankingEntity();
row.competitorid = a.competitorid;
row.firstname = a.firstname;
row.lastname = a.lastname;
row.academy = a.academy;
row.points = a.points;
row.place = a.place;
row.eventId = a.eventId;
row.eventname = a.eventname;
row.categoryname = a.categoryname;
row.Rank = item.Rank;
ttt.Add(row);
}
我得到的结果如下:
请帮助我做错了什么。
答案 0 :(得分:1)
您要实现的目标是对“组”进行排名,然后按结果对结果进行分组,然后对组进行排序。对于组中的每个项目,给出相同的等级。
finalResult.GroupBy(item => item.Points) // Group by points
.OrderDescendingBy(g => g.Key) // Order the groups
.Select((g, index) => new { Data = g, GroupRank = index + 1}) // Rank each group
.SelectMany(g => g.Data.Select(item => new RankingEntity
{
/* properties of each item */
Rank = g.GroupIndex
}); // Flatten groups and set for each item the group's ranking
您方法中的问题是您为单个项目而不是组提供排名。然后,当您检索组的等级(from i in finalResult let rank = finalResult.First(x => x.points == i.points)...
)时,您实际为组中的每个项目设置了其中一个元素的排名。因此,如果您首先获得该组的最后一项 - 那将是其中每个项目的Rank值。
另请注意,在代码的第一行中,您使用ToList
。因此,不需要在它下面的行中使用AsEnumerable
- 它已经在内存集合中实现了。