按降序错误命令LINQ

时间:2016-07-20 14:12:43

标签: c# sql-server linq ienumerable iqueryable

这主要是一个好奇心,而不是一个真正的问题,因为我已经修复了这个bug。我很乐意有一个深刻的答案来解释这个魔法背后的LINQ机制。所以我有这个问题:

List<List<IMS_CMM_Measurement>> imsCMMMeasurements = 
    (from i in context.IMS_CMM_Measurement
     where i.Job_FK == jobId 
        && currentOperationCharacteristics.Contains(i.Characteristic_FK)
     select i)
    .GroupBy(elm => elm.Characteristic_FK)
    .Select(CharacGroup => CharacGroup.GroupBy(elm => elm.Part_Number))
    .Select(CharacGroup => CharacGroup.Select(PartGroup => PartGroup.OrderByDescending(measure => measure.Timestamp)))
    .Select(CharacGroup => CharacGroup.Select(PartGroup => PartGroup.FirstOrDefault()))
    .Select(CharacGroup => CharacGroup.OrderBy(measure => measure.Part_Number))
    .Select(CharacGroup => CharacGroup.ToList()).ToList();

基本上,它从数据库中进行测量并按特征对其进行分组。对于每个特征,有几个对应于不同部分的度量,并且一些部分被测量不止一次。在后一种情况下,我们只采用最近的一个度量(具有最大时间戳的度量,即日期格式条目)。为了做到这一点,我必须按时间戳按递减顺序为每个部分订购度量。不幸的是,这恰恰相反:它采取最古老的措施。

我设法通过这样做得到了相应的结果(在第4行的LINQ查询末尾添加了.ToList()):

List<List<IMS_CMM_Measurement>> imsCMMMeasurements = 
    (from i in context.IMS_CMM_Measurement
     where i.Job_FK == jobId 
        && currentOperationCharacteristics.Contains(i.Characteristic_FK)
     select i).ToList()
    .GroupBy(elm => elm.Characteristic_FK)
    .Select(CharacGroup => CharacGroup.GroupBy(elm => elm.Part_Number))
    .Select(CharacGroup => CharacGroup.Select(PartGroup => PartGroup.OrderByDescending(measure => measure.Timestamp)))
    .Select(CharacGroup => CharacGroup.Select(PartGroup => PartGroup.FirstOrDefault()))
    .Select(CharacGroup => CharacGroup.OrderBy(measure => measure.Part_Number))
    .Select(CharacGroup => CharacGroup.ToList()).ToList();        

为什么现在这样做? ;)

0 个答案:

没有答案