Linq添加额外列(最大日期)

时间:2016-04-02 13:24:03

标签: c#

我有班级学生,考试集合,每个考试都有标题和日期。 在我的视图模型中,我想显示每个学生的每个考试的网格,但我想添加额外的列与最新的考试日期(我知道这将重复每行,但这是它的请求。

public class Student
{
    public int Id { get; set; }
    public int Name { get; set; }
    public IEnumerable<Exam> Exams { get; set; }
}

public class Exam
{
    public int StudentId { get; set; }
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime ExamDate { get; set; }
}

public class ExamViewModel
{
    public string StudentName { get; set; }
    public string ExamTitle { get; set; }
    public DateTime ExamDate { get; set; }
    public Exam LastExam { get; set; }
}

在每一行中,我想把Max上次考试日期

var list = (from s in uow.Students.GetAll()
            join e in uow.Exams.GetAll() on s.Id equals e.StudentId
            select new ExamViewModel
            {
                StudentName = s.Name,
                ExamTitle = e.Title,
                ExamDate = e.ExamDate,
                LastExam =???
            });

结果应该是这样的

  • 名称----------------- ExamTitle ------日期----------------- LatestExamDate
  • Mike Peter --------- French ------- 15/03/2015 --------- 20/12/2015
  • Mike Peter ---------数学---------- 16/03/2015 --------- 20/12/2015
  • Mike Peter --------- UML ---------- 20/12/2015 -------- 2015年12月20日
  • David Ula ---------- C#------------ 12/12/2015 -------- 14/12/2015
  • David Ula ---------- VB ------------ 16/09/2015 --------- 14/12/2015
  • David Ula ---------- Bio ---------- 14/12/2015 --------- 14/12/2015
  • David Ula ---------- Mngmt --------- 10/10/2015 --------- 14/12/2015

2 个答案:

答案 0 :(得分:1)

您可以正确配置双向导航,以使此查询更加简单。

将以下属性添加到Exam

public virtual Student Student { get; set; }

然后将其配置为使用现有的StudentID

您的查询将变为:

uow.Exams().GetAll().Select(e => new {
    StudentName = e.Student.Name,
    ExamTitle = e.Title,
    ExamDate = e.ExamDate,
    LastExamDate = e.Student.Exams.Max(e => e.ExamDate)
})

或者,您需要这样做:

var list = (from s in uow.Students.GetAll()
        join e in uow.Exams.GetAll() on s.Id equals e.StudentId
        select new ExamViewModel
        {
            StudentName = s.Name,
            ExamTitle = e.Title,
            ExamDate = e.ExamDate,
            LastExamDate = uow.Exams.GetAll().Where(e => e.StudentId == s.Id).Max(e => e.ExamDate)
        });

答案 1 :(得分:0)

var list = (from s in uow.Students.GetAll()
            join e in uow.Exams.GetAll() on s.Id equals e.StudentId
            select new ExamViewModel
            {
                StudentName = s.Name,
                ExamTitle = e.Title,
                ExamDate = e.ExamDate,
                LastExamDate = uow.Exams.GetAll().OrderByDescending(x=> x.ExamDate).First(x=> x.StudentId = s.Id)
            });