我整个上午一直在困惑这个问题,无法弄清楚如何在C#中做到这一点。
我的SQL查询如下:
select a.CourseID,
a.UserID
from audit a
inner join results r on a.UserID = r.UserID
inner join Course c on a.CourseID = c.CourseID
where c.CourseType = 9 and a.Guid = 'A123F123D123AS123123'
and a.Result = 'Passed' and r.Class = 'Maths'
group by a.CourseID, a.UserID
order by a.UserID
完全返回我想要的内容,但我似乎无法将其翻译成linq格式。 (此处使用的格式是我目前工作所需的格式,因此请以此格式提供建议)
到目前为止,我有以下内容:
var audits = auditRepository.Get(a => a.Course.CourseType == 9 && a.GUID == this.Company.GUID && a.Result == "Passed", null, null,
a => a.Course, a => a.User)
.Join(resultsRepository.Get(r => r.GUID == this.Company.GUID && r.Class == class),
a => a.UserID,
r => r.UserID,
(a, r) => new Audit
{
User = a.User,
Course = a.Course,
Result = a.Result,
Timestamp = a.Timestamp,
AuditID = a.AuditID,
UserID = a.UserID
}
)
.OrderByDescending(o => o.Timestamp)
.GroupBy(u => new { u.User, u.Course })
.Select(grp => grp.ToList())
.ToList();
然而,这会返回重复项。
感谢任何建议,谢谢
ħ
答案 0 :(得分:2)
而不是
.Select(grp => grp.ToList())
仅选择每个组中的第一个元素以排除重复项:
.Select(grp => grp.First())
如果您还需要点数:
.Select(t => new{grp = t.First(),cnt = t.Count()} )
<强>修正:强>
.Select(t => new { grp = t.First(), cnt = t.Select(s => s.AuditID).Distinct().Count() })