在此列表中,教师可以拥有多个SchoolEndYears。我想修改这个查询,所以我只抓住每个老师的最大值。
代码:
var gridInfo = (from teacher in TeacherAccesses
join u in USERS
on teacher.ID equals u.ID
select new
{
Name = u.LastName + ", " + u.FirstName,
ID = teacher.ID,
Flag = "Existing",
SchoolID = teacher.SchoolID,
status = teacher.TeacherAttr.IncludeinOfficialResults.Value,
SchoolEndYear = teacher.TeacherAttr.SchoolEndYear
}).OrderByDescending(x=>x.SchoolEndYear).OrderBy(x=>x.Name);
正如您所看到的,我尝试了.OrderByDescending
,但当我尝试.FirstOrDefault
时,它只会带回群组中的第一条记录。
我希望带回来的是:
答案 0 :(得分:1)
我认为你想要的东西如下,虽然我不确定这是多么有效:
var gridInfo = (from teacher in TeacherAccesses
join u in USERS
on teacher.ID equals u.ID
where teacher.Year = TeacherAccesses.Where(x => x.ID = teacher.ID)
.Max(x => x.TeacherAttr.SchoolEndYear)
select new
{
Name = u.LastName + ", " + u.FirstName,
ID = teacher.ID,
Flag = "Existing",
SchoolID = teacher.SchoolID,
status = teacher.TeacherAttr.IncludeinOfficialResults.Value,
SchoolEndYear = teacher.TeacherAttr.SchoolEndYear
});
这是一个简化的LINQPad示例:
void Main()
{
var TeacherAccesses = new List<Teacher>() {
new Teacher() { ID = 1, Name = "Teacher-A", TeacherAttr = new Attr() { SchoolEndYear = 2012 } },
new Teacher() { ID = 1, Name = "Teacher-A", TeacherAttr = new Attr() { SchoolEndYear = 2013 } },
new Teacher() { ID = 1, Name = "Teacher-A", TeacherAttr = new Attr() { SchoolEndYear = 2014 } },
new Teacher() { ID = 2, Name = "Teacher-B", TeacherAttr = new Attr() { SchoolEndYear = 2012 } },
new Teacher() { ID = 2, Name = "Teacher-B", TeacherAttr = new Attr() { SchoolEndYear = 2013 } },
new Teacher() { ID = 3, Name = "Teacher-C", TeacherAttr = new Attr() { SchoolEndYear = 2012 } }
};
//TeacherAccesses.Dump();
var latest =
from teacher in TeacherAccesses
where teacher.TeacherAttr.SchoolEndYear == TeacherAccesses.Where(x => x.ID == teacher.ID).Max(x => x.TeacherAttr.SchoolEndYear)
select new {
Name = teacher.Name,
Year = teacher.TeacherAttr.SchoolEndYear
};
latest.Dump();
}
// Define other methods and classes here
public class Teacher
{
public int ID { get; set; }
public string Name { get; set; }
public Attr TeacherAttr { get; set; }
}
public class Attr
{
public int SchoolEndYear { get; set; }
}
结果:
Teacher-A 2014
Teacher-B 2013
Teacher-C 2012
答案 1 :(得分:1)
您需要的是将同一位教师的记录组合在一起,然后应用Max
函数,以便您找到该组的最大元素:
var gridInfo = (from teacher in TeacherAccesses
...
})
.GroupBy(x => x.ID)
.Select(g => g.Max(x => x.SchoolEndYear))
.OrderBy(x => x.Name);