Skip to main content
 首页 » 编程设计

C# LINQ 查询

2024年02月23日13xing901022

我在包含以下数据的用户定义类型列表中有一些数据:

姓名、研究、小组、结果、日期。现在我想获取名称、研究和组,然后根据结果和日期进行计算。计算有效:

log(result).where max(date) minus log(result).where min(date) 

每个名称/研究/组只有两个日期,因此最大数据(log)的结果减去最小日期(log)的结果。这是我到目前为止没有运气的尝试:

 var result =  
    from results in sortedData.AsEnumerable() 
    group results by results.animal 
    into grp 
    select new 
    { 
         animal = results.animal, 
         study = results.study, 
         groupNumber = results.groupNumber, 
         TGI = System.Math.Log(grp.Select(c => c.volume) 
                                  .Where(grp.Max(c=>c.operationDate))) 
             - System.Math.Log(grp.Select(c => c.volume) 
                                  .Where(grp.Min(c => c.operationDate))) 
    }; 

有人指点吗?谢谢。

请您参考如下方法:

分组与您的问题的关系并不完全清楚(在分组后从范围变量中提取属性有什么意义?),但是您的部分使用 MaxBy 可以轻松解决困难和 MinBy运算符,例如 morelinq 附带的运算符.

var result = from results in sortedData.AsEnumerable() 
             group results by results.animal into grp 
             select new 
             { 
                animal = grp.Key, 
                study = ??, 
                groupNumber = ??, 
                TGI  =  Math.Log(grp.MaxBy(c => c.operationDate).volume)  
                      - Math.Log(grp.MinBy(c => c.operationDate).volume)     
              }; 

否则,你可以用Aggregate模拟这些运算符,或者如果你不介意排序的低效:

var result = from results in sortedData.AsEnumerable() 
             group results by results.animal into grp 
 
             let sortedGrp = grp.OrderBy(c => c.operationDate) 
                                .ToList() 
             select new 
             { 
                animal = grp.Key, 
                study = ??, 
                groupNumber = ??, 
                TGI  = sortedGrp.Last().volume  - sortedGrp.First().volume                
             };