views:

129

answers:

2

New to LINQ.. I am curious as to the syntax to do the following SQL query in LINQ

SELECT MAX(TMPS), DAY FROM WEATHERREADINGS
GROUP BY WEATHERREADINGS.DAY

What I have so far:

var minTemps = from ps in ww.WEATHERREADINGS
               group ps by ps.DATE.Hour into psByHour
               select new
               {
                   HourOfDay = psByHour.Max().DATE.Hour,
                   MaxTemp = psByHour.Max().TMPS
               };

I am getting the following error while doing this:

Exception Details: System.InvalidOperationException: Could not format node 'New' for execution as SQL.

any help greatly appreciated!!

+5  A: 

I think the following is what you want. Note that you can get the key from the grouping so there is no need to aggregate there. You need to provide a mechanism to select the item to do the aggregation on for the other.

var maxTemps = from ps in ww.WEATHERREADINGS
               group ps by ps.Date.Hour into psByHour
               select new
               {
                    HourOfDay = psByHour.Key,
                    MaxTemp = psByHour.Max( p => p.TMPS )
               };
tvanfosson
Beat me by a few seconds +1
Jose Basilio
nice catch with the "maxTemps" instead of "minTemps" *hehe*
andyp
exactly what i was looking for thank you. now i can use this as a datasource and bind it to a grid
Will
+1  A: 

Or the functional approach that i tend to like better:

var result = ww.WEATHERREADINGS
                .GroupBy(a => a.Date.Hour)
                .Select(a => new
                       {
                         Hour = a.Key,
                         Max = a.Max(b => b.TMPS)
                       });
AZ
+1 I agree, but I try to answer in the format the OP asks unless there's a compelling reason otherwise.
tvanfosson
Your answer was spot on and correct (+1). I just wanted to provide the alternative. I tend to find that a lot of my junior mates tend to treat Linq just as a little SQL addon in C# and do not see the bigger picture of functional ways of doing things. When i expose them to the functional syntax then enlightment follows.
AZ