LINQ使用相应的时间字段查找最大/最小值

时间:2011-06-11 03:08:50

标签: c# .net linq linq-to-sql linq-to-objects

我有一张气象站的数据记录表,我将查询结果转换为WPF ListBox

表结构是:

  • 日期
  • 时间
  • 温度
  • rain_today
  • 湿度

我的查询工作正常:

var q = from c in db.Apr11log
                group c by c.LogDate into g
                orderby g.Key
                select new
                {
                    LogDate = g.Key,
                    MaxTemp = g.Max(c => c.Temp),
                    MinTemp = g.Min(c => c.Temp),                                             
                    Rain = g.Max(c => c.Rain_today),
                };      

但是我试图得到Max Temp和Min Temp的相应时间,即

TimeMax = .....
TimeMin = .....

我用Google搜索并用谷歌搜索,但没有发现任何有用的东西。

2 个答案:

答案 0 :(得分:5)

var q = from c in db.Apr11log
        group c by c.LogDate into g
        orderby g.Key
        select new
        {
            LogDate = g.Key,
            MaxRow = g.OrderByDescending(c => c.Temp).Select(c => new { c.LogDate, c.Temp }).First(),
            MinRow = g.OrderBy(c => c.Temp).Select(c => new { c.LogDate, c.Temp }).First(),
            Rain = g.Max(c => c.Rain_today),
        };

var q = from c in db.Apr11log
        group c by c.LogDate into g
        orderby g.Key
        let maxRow = g.OrderByDescending(c => c.Temp).First()
        let minRow = g.OrderBy(c => c.Temp).First()
        select new
        {
            LogDate = g.Key,
            MaxTemp = maxRow.Temp,
            MaxTempDate = maxRow.LogDate,
            MinTemp = minRow.Temp,
            MinTempDate = minRow.LogDate,
            Rain = g.Max(c => c.Rain_today),
        };

答案 1 :(得分:0)

let maxTemp = c.Max(c=>c.Temp)
let minTemp = c.Min(c=>c.Temp)
select new {
    LogDate = g.Key,
    MaxTemp = maxTemp,
    MinTemp = minTemp,
    MaxTime = g.FirstOrDefault(c=>c.Temp = maxTemp).Time,
    MinTime = g.FirstOrDefault(c => c.Temp = minTemp).Time,
    Rain = g.Max(c => c.Rain_today),
       };