简体   繁体   English

Linq for SQL(等效于SQL Server) -

[英]Linq for rank() equivalent in SQL Server -

How can order my list using Linq equals rank() over in SQL ? 如何使用Linq命令我的列表等于SQL中的rank()?

For example rank is my List<Player> 例如,rank是我的List<Player>

class Player
{
    public int Id;
    public int RankNumber;
    public int Points;
    public int Name;

}

Original Rank list: 原始排名列表:

RankNumber   Points  Name    Id
    1          100    James   01
    2          80     Mike    50
    3          80     Jess    22
    4          50     Jack    11
    5          50     Paul    03  
    6          10     Monik   13

I need this Rank: 我需要这个等级:

RankNumber   Points  Name    Id
    1          100    James   01
    2          80     Mike    50
    2          80     Jess    22
    4          50     Jack    11
    4          50     Paul    03  
    6          10     Monik   13

I don't think there is a good way to convert this directly to Linq to SQL but you could do this: 我不认为有一种很好的方法可以将它直接转换为Linq to SQL,但你可以这样做:

var rankedPlayers = players
    .OrderByDescending(p => p.Points)
    .Select((p, r) => new Player
    {
        Id = p.Id,
        RankNumber = players.Where(pl => pl.Points > p.Points).Count() + 1,
        Points = p.Points,
        Name = p.Name
    });

It gives you the correct output but will convert horribly and inefficiently to SQL. 它为您提供了正确的输出,但会以可怕的低效率转换为SQL。 So I would suggest this modification which materialises the data to a list before creating the ranks: 所以我建议这个修改在创建排名之前将数据实现到列表中:

var rankedPlayers = players
    .OrderByDescending(p => p.Points)
    .ToList() //<--- Add this
    .Select((p, r) => new Player
    {
        Id = p.Id,
        RankNumber = players.Where(pl => pl.Points > p.Points).Count() + 1,
        Points = p.Points,
        Name = p.Name
    });

You can try below expression: 您可以尝试以下表达式:

var newData = players
             .OrderByDescending(x => x.Points)
             .GroupBy(x => x.Points)                 
             .SelectMany((x, index) => x.Select(y => new Player
            {
                Name = y.Name,
                Points = y.Points,
                RankNumber = index + 1,
                Id = y.Id
            }));

players contains IEnumerable of objects of type Player and newData contains ordered data with rank. players包含IEnumerable的类型的球员和对象的newData包含等级排序数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM