目的: 查询结构物下所有网关的最新诊断结果.
1. 正确查询 (按诊断时间倒序)
var query = queryDiag.GroupBy(g => new {g.dtuId, g.dtuNo, g.dtuDesp}) .Select(s => s.GroupBy(r => r.diagTime) .Select(e => new { s.Key.dtuId, s.Key.dtuNo, s.Key.dtuDesp, diagTime = e.Key, cpuRatio = e.Where(w => w.diagName == iDAUDiagEntity.CpuRatio) .Select(l => l.diagResult).FirstOrDefault(), memoryRatio = e.Where(w => w.diagName == iDAUDiagEntity.MemoryRatio) .Select(l => l.diagResult).FirstOrDefault(), flashRatio = e.Where(w => w.diagName == iDAUDiagEntity.FlashRatio) .Select(l => l.diagResult).FirstOrDefault(), sdRatio = e.Where(w => w.diagName == iDAUDiagEntity.SdRatio) .Select(l => l.diagResult).FirstOrDefault(), gatewayWorkDuration = e.Where(w => w.diagName == iDAUDiagEntity.GatewayWorkDuration) .Select(l => l.diagResult).FirstOrDefault(), serverWorkDuration = e.Where(w => w.diagName == iDAUDiagEntity.ServerWorkDuration) .Select(l => l.diagResult).FirstOrDefault(), nodesCount = e.Select(l => l.nodesCount).FirstOrDefault() }).OrderByDescending(o => o.diagTime).FirstOrDefault());
查询结果:
结构下每个网关的最新诊断结果.
2. 错误查询 (未实现排序目的)
如果将查询语句中的 ".OrderByDescending()" 调整下位置, 如下代码所示:
var query = queryDiag.GroupBy(g => new {g.dtuId, g.dtuNo, g.dtuDesp}) .Select(s => s.OrderByDescending(o => o.diagTime).GroupBy(r => r.diagTime) .Select(e => new { s.Key.dtuId, s.Key.dtuNo, s.Key.dtuDesp, diagTime = e.Key, cpuRatio = e.Where(w => w.diagName == iDAUDiagEntity.CpuRatio) .Select(l => l.diagResult).FirstOrDefault(), memoryRatio = e.Where(w => w.diagName == iDAUDiagEntity.MemoryRatio) .Select(l => l.diagResult).FirstOrDefault(), flashRatio = e.Where(w => w.diagName == iDAUDiagEntity.FlashRatio) .Select(l => l.diagResult).FirstOrDefault(), sdRatio = e.Where(w => w.diagName == iDAUDiagEntity.SdRatio) .Select(l => l.diagResult).FirstOrDefault(), gatewayWorkDuration = e.Where(w => w.diagName == iDAUDiagEntity.GatewayWorkDuration) .Select(l => l.diagResult).FirstOrDefault(), serverWorkDuration = e.Where(w => w.diagName == iDAUDiagEntity.ServerWorkDuration) .Select(l => l.diagResult).FirstOrDefault(), nodesCount = e.Select(l => l.nodesCount).FirstOrDefault() }).FirstOrDefault());
查询结果:
没有达到预期结果, 可能是最晚的一条诊断记录, 也可能是历史诊断中的某一条记录.
【小结】
IQueryable 查询语句中 OrderByDescending() 扩展方法使用时需注意:
如果需要将结果集按时间倒序排列, 则需要将 "OrderByDescending()" 扩展方法置后.
置前的话, LINQ语句转换后的SQL语句中没有 "order by" 排序条件, 故此, 达不到倒序的效果.
时间: 2024-10-25 15:06:28