如何将行号投影到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 ++”行引发了以下编译时异常:
“表达式树可能不包含赋值运算符”
答案 0 :(得分: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();
}
}
答案 1 :(得分:1)
好的,这就是诀窍。感谢。
这是我的最终代码......
服务器:
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();
}
答案 2 :(得分:0)
您还可以对原始代码稍作调整,以使其正常工作。请注意,如果您再次数据绑定或访问对象,Rank将每次递增。在这些情况下,最佳答案是更好的。
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>();
}
}
答案 3 :(得分:0)
这个解决方案对我有用。 http://www.dotnetfunda.com/articles/article1995-rownumber-simulation-in-linq.aspx
.Select((x, index) => new
{
SequentialNumber = index + 1
,FieldFoo = x.FieldFoo
}).ToList();
答案 4 :(得分:0)
列表 Lstemp = GetEmpList(); int Srno = 0; var列=以Lstemp顺序中的t从t开始。名称选择新的{Row_number = ++ Srno,EmpID = t.ID,名称= t.Name,城市= t.City};