如何将行号投影到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)