tags:

views:

9188

answers:

2

Hi,

I'm having a hard time understanding how I can form a LINQ query to do the following:

I have a table CallLogs and I want to get back a single result which represents the call that has the longest duration.

The row looks like this:

[ID] [RemoteParty] [Duration]

There can be multiple rows for the same RemoteParty, each which represents a call of a particular duration. I'm wanting to know which RemoteParty has the longest total duration.

Using LINQ, I got this far:

var callStats = (from c in database.CallLogs
                 group c by c.RemoteParty into d
                 select new
                 {
                      RemoteParty = d.Key,
                      TotalDuration = d.Sum(x => x.Duration)
                 });

So now I have a grouped result with the total duration for each RemoteParty but I need the maximum single result.

[DistinctRemoteParty1] [Duration]

[DistinctRemoteParty2] [Duration]

[DistinctRemotePartyN] [Duration]

How can I modify the query to achieve this?

Thanks in advance,

Martin.

+3  A: 

Order the result and return the first one.

var callStats = (from c in database.CallLogs
                 group c by c.RemoteParty into d
                 select new
                 {
                      RemoteParty = d.Key,
                      TotalDuration = d.Sum(x => x.Duration)
                 });

callStats = callStats.OrderByDescending( a => a.TotalDuration )
                     .FirstOrDefault();
tvanfosson
I presume that the "a.Duration > b.Duration" expression should actually read "a.TotalDuration > b.TotalDuration"?
Zooba
+1 to Zooba's comment
configurator
Yep. Missed that. Fixed now.
tvanfosson
Why is it not just OrderBy(a => a.TotalDuration)?
Jon Skeet
because I didn't bother to look at the documentation and didn't actually try it. :-)
tvanfosson
Oops. Need to order by descending since it's not using a comparision and we want the max.
tvanfosson
+2  A: 

Have a look at the "Max" extension method from linq

callStats.Max(g=>g.TotalDuration);
flq
That would only return the maximum TotalDuration without the RemoteParty part.
configurator