如何将行号投影到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 ++”行会引发下面的编译时exception:
“expression式树可能不包含赋值运算符”
那么,最简单的方法是在客户端而不是数据库端执行,并使用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(); } }
好的,那就是诀窍。 谢谢。
这是我最终的代码…
服务器:
public List<Score> GetHighScores(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 s; return query.ToList<Score>(); } }
客户:
void hsc_LoadHighScoreCompleted(object sender, GetHighScoreCompletedEventArgs e) { ObservableCollection<Score> list = e.Result; _listBox.ItemsSource = list.Select((player, index) => new ScoreWithRank() { PlayerName = player.PlayerName, PlayerScore = player.PlayerScore, Rank = index+=1 }).ToList(); }
您也可以对原始代码进行一些微调,以使其工作。 谨慎的话,如果你再次绑定或访问对象,秩会每次增加。 在这些情况下,最好的答案是更好的。
let Rank = i++
和
Rank.ToString()
完整代码:
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 let Rank = i++ where s.Game.Id == guid orderby s.PlayerScore descending select new ScoreWithRank() { Rank.ToString(), PlayerName = s.PlayerName, PlayerScore = s.PlayerScore }; return query.ToList<ScoreWithRank>(); }
}
这个解决scheme为我工作。 http://www.dotnetfunda.com/articles/article1995-rownumber-simulation-in-linq.aspx
.Select((x, index) => new { SequentialNumber = index + 1 ,FieldFoo = x.FieldFoo }).ToList();