我有这样的功能
$('td div.modal').siblings('a')
private List<Score> getPageNRows ( int N )
{
// Returns object corresponding to the rows of the table
// on "page" N of the scores page
return (from s in this._SD.Scores
orderby s.score1 descending
select s)
.Skip(ScoresController._scoresPerPage * (N - 1))
.Take(ScoresController._scoresPerPage * N)
.ToList();
}
由
Score
在这里,我真正想要的是public partial class Score
{
public Score()
{
GameLogs = new HashSet<GameLog>();
}
public int id { get; set; }
[Column("score")]
public int score1 { get; set; }
[StringLength(50)]
public string name { get; set; }
public DateTime playdate { get; set; }
public virtual ICollection<GameLog> GameLogs { get; set; }
}
,其中List<ViewScore>
由
ViewScore
这可以在LINQ查询中完成所有操作,还是需要创建辅助方法?
至少,我如何只选择public class ViewScore
{
public int score { get; set; } // corresponds directly to score1 in Score class
public string name { get; set; } // corresponds directly to name in Score
public string datestr { get; set; } // corresponds to playdate.ToString()
}
,s.score1
和s.name
列而不是所有列(通过s.playdate
)?
答案 0 :(得分:2)
是的,您可以使用Linq
这样的
return this._SD.Scores
.OrderByDescending(s => s.score1)
.Skip(ScoresController._scoresPerPage * (N - 1))
.Take(ScoresController._scoresPerPage * N))
.Select(s => new ViewScore { score = s.score1, name = s.name, datestr = s.playdate.ToString() })
.ToList();
答案 1 :(得分:0)
我建议使用lambda路径:
private List<Score> getPageNRows ( int N )
{
// Returns object corresponding to the rows of the table
// on "page" N of the scores page
return this._SD.Scores.OrderByDescending(c => c.score1)
.Skip(ScoresController._scoresPerPage * (N - 1))
.Take(ScoresController._scoresPerPage * N)
.ToList();
}
根据MSDN,查询语法不支持skip and take:See Here。
看到这个stack overflow question问了类似的事情。
现在,如果您想将Score
课程投射到ViewScore
课程中,只需添加Select<TSource, TResult>
语句:
private List<ViewScore> getPageNRows ( int N )
{
// Returns object corresponding to the rows of the table
// on "page" N of the scores page
return this._SD.Scores.OrderByDescending(c => c.score1)
.Skip(ScoresController._scoresPerPage * (N - 1))
.Take(ScoresController._scoresPerPage * N)
.Select(c => new ViewScore()
{
score = c.score1,
name = c.name,
datestr = c.playdate.ToString()
})
.ToList();
}
答案 2 :(得分:0)
可以使用投影仅返回选定的列。方法Select()
用于投影:
return (from s in this._SD.Scores
orderby s.score1 descending
select s
).Skip(ScoresController._scoresPerPage * (N - 1)
).Take(ScoresController._scoresPerPage * N)
.Select(x => new ViewScore() { score = x.score1, name = x.name, datestr = x.playdate })
.ToList();
在使用Select()
查询实现之前使用ToList()
非常方便将从DB返回的数据限制为真正需要的内容。