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

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

问题描述

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

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

而不是说:

字段 1、字段 2、字段 3

field1, field2, field3

字段 1、字段 2、字段 3

field1, field2, field3

我想:

1、字段 1、字段 2、字段 3

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天全站免登陆