如何将行号投射到Linq查询结果中

Jef*_*ber 34 linq row-number

如何将行号投影到linq查询结果集上.

而不是说:

field1,field2,field3

field1,field2,field3

我想要:

1,field1,field2,field3

2,field1,field2,field3

以下是我对此的尝试:

public List<ScoreWithRank> GetHighScoresWithRank(string gameId, int count)
{
    Guid guid = new Guid(gameId);
    using (PPGEntities entities = new PPGEntities())
    {
        int i = 1;
        var query = from s in entities.Scores
                    where s.Game.Id == guid
                    orderby s.PlayerScore descending
                    select new ScoreWithRank()
                    {
                        Rank=i++,
                        PlayerName = s.PlayerName,
                        PlayerScore = s.PlayerScore
                    };
        return query.ToList<ScoreWithRank>();
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,"Rank = i ++"行引发了以下编译时异常:

"表达式树可能不包含赋值运算符"

Jon*_*eet 55

嗯,最简单的方法是在客户端而不是数据库端执行它,并使用Select的重载,它也提供索引:

public List<ScoreWithRank> GetHighScoresWithRank(string gameId, int count)
{
    Guid guid = new Guid(gameId);
    using (PPGEntities entities = new PPGEntities())
    {
        var query = from s in entities.Scores
                    where s.Game.Id == guid
                    orderby s.PlayerScore descending
                    select new
                    {
                        PlayerName = s.PlayerName,
                        PlayerScore = s.PlayerScore
                    };

        return query.AsEnumerable() // Client-side from here on
                    .Select((player, index) => new ScoreWithRank()
                            {
                                PlayerName = player.PlayerName,
                                PlayerScore = player.PlayerScore,
                                Rank = index + 1;
                            })
                    .ToList();

    }
}
Run Code Online (Sandbox Code Playgroud)

  • @MikeKulls:因为你不能用LINQ做*all*数据库的东西,你做*没有*吗?这听起来就像把洗澡水扔给我一样. (7认同)
  • @DotNetWise:我同意`count`参数还没有被使用,但是只要在'AsEnumerable()`调用之前使用*,就可以了.特别是`where`子句和`orderby`子句在`AsEnumerable`之前使用,因此所有过滤都将在数据库中进行.正如我在之前的评论中所说,它只获得与查询匹配的记录...换句话说,无论如何都需要的数据.如果你想获得排在第20位之后的位置,你可以在`query`中添加一个`Skip`调用,或者使用`query.Skip(20).AsEnumerable()`.(然后你想调整`Rank'计算.) (6认同)
  • 从数据库中获取所有内容并不是真正的"解决方案" (3认同)