如何将行号投影到 Linq 查询结果中
如何将行号投影到 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>();
}
}
不幸的是,“Rank=i++”行抛出以下编译时异常:
“表达式树可能不包含赋值运算符”
How can I project the row number onto the linq query result set.
Instead of say:
field1, field2, field3
field1, field2, field3
I would like:
1, field1, field2, field3
2, field1, field2, field3
Here is my attempt at this:
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>();
}
}
Unfortunately, the "Rank=i++" line throws the following compile-time exception:
"An expression tree may not contain an assignment operator"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,最简单的方法是在客户端而不是数据库端执行此操作,并使用也提供索引的 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:
好的,这就成功了。 谢谢。
这是我的最终代码...
服务器:
客户端:
Ok, that did the trick. Thanks.
Here is my final code...
Server:
Client:
您还可以对原始代码进行轻微调整以使其正常工作。 请注意,如果您再次进行数据绑定或访问该对象,排名每次都会增加。 在这些情况下,最佳答案更好。
和
完整代码:
}
You could also make just a slight adjustment to your original code to get it working. Word of caution, if you databind or access the object again, the Rank will increment each time. In those cases the top answer is better.
and
Full code:
}
这个解决方案对我有用。
http://www.dotnetfunda.com/articles/article1995-rownumber -simulation-in-linq.aspx
This solution worked for me.
http://www.dotnetfunda.com/articles/article1995-rownumber-simulation-in-linq.aspx