如何将行号投影到Linq查询结果中 [英] How To Project a Line Number Into Linq Query Results

查看:56
本文介绍了如何将行号投影到Linq查询结果中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I project the row number onto the linq query result set.

代替说:

field1,field2,field3

field1, field2, field3

field1,field2,field3

field1, field2, field3

我想要:

1,field1,field2,field3

1, field1, field2, field3

2,字段1,字段2,字段3

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>();
    }
}

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

Unfortunately, the "Rank=i++" line throws the following compile-time exception:

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

"An expression tree may not contain an assignment operator"

推荐答案

好吧,最简单的方法是在客户端而不是在数据库端进行操作,并使用Select的重载功能(该功能还提供了索引):

Well, the easiest way would be to do it at the client side rather than the database side, and use the overload of Select which provides an index as well:

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();

    }
}

这篇关于如何将行号投影到Linq查询结果中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆