Corretto
Corretto

Reputation: 67

LINQ find max/min value with corresponding time fields

I have a table of data recordings from a weather station from which I am querying results into a WPF ListBox.

The table structure is:

I have a query which works fine:

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),
                };      

However I am trying to get the corresponding time of the Max Temp and Min Temp, i.e.

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

I've googled and googled but found nothing useful.

Upvotes: 2

Views: 1149

Answers (2)

Alex Aza
Alex Aza

Reputation: 78447

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),
        };

or

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),
        };

Upvotes: 5

Waleed
Waleed

Reputation: 3145

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),
       };      

Upvotes: 0

Related Questions