c# - 是否可以在单个 LINQ 查询中完成所有这些操作?

标签 c# asp.net asp.net-mvc algorithm linq

我有这样的功能

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

定义
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()
}

这是否可以在 LINQ 查询中完成所有操作,或者我是否需要创建辅助方法?

至少,我如何只选择列 s.score1 , s.names.playdate而不是全部(通过 select )?

最佳答案

是的,你可以像这样用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();      

关于c# - 是否可以在单个 LINQ 查询中完成所有这些操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33448655/

相关文章:

c# - 正则表达式:如何不匹配单词的最后一个字符?

javascript - ASP.NET MVC 多选列表框值未呈现

Javascript:使用 ActiveXobject 保存文件

ASP.NET 5 DNX : How to shutdown application properly?

c# - Web Api 的 CreateResponse<Content>() 和 CreateResponse() 之间有什么区别吗?

c# - 在 ASP 转发器中设置 CheckBox "Checked"属性

c# - BlobServiceClient应该如何创建?

javascript - 如何全屏打开目标="_blank"?

asp.net-mvc - MVC T4 MvcTextTemplateHost和自定义的“ Controller ” T4模板

asp.net-mvc - ASP.NET MVC 本地化最佳实践?