如何将 linq 查询转换为非查询表达式

本文关键字:查询 查询表 表达式 转换 linq | 更新日期: 2023-09-27 17:55:44

我使用 EF6,我有这个 linq 到实体查询:

   from s in SensorObservationEntities.SensorsMeasures
            group s by s.SensorUnitId into g
            let latest = g.OrderByDescending(s => s.MeasureDate).FirstOrDefault()
            select latest

我怎样才能把它觊觎到非查询表达式?

如何将 linq 查询转换为非查询表达式

你的意思是方法语法:

SensorObservationEntities.SensorsMeasures.GroupBy(g => g.SensorUnitId)
             .Select(y => y.OrderByDescending(x => x.MeasureDate).FirstOrDefault());

如果要将其转换为方法语法版本,可以逐步执行此操作。我喜欢从最后开始,一直工作到开头:

  1. select to Select 定义源:

    .Select(g => g.OrderByDescending(s => s.MeasureDate).FirstOrDefault());
    
  2. group GroupBy

    .GroupBy(s => s.SensorUnitId)
    .Select(g => g.OrderByDescending(s => s.MeasureDate).FirstOrDefault());
    
  3. from

    SensorObservationEntities.SensorsMeasures
    .GroupBy(s => s.SensorUnitId)
    .Select(g => g.OrderByDescending(s => s.MeasureDate).FirstOrDefault());