Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Group By with Max Date and count

I have the following SQL

SELECT  Tag , COUNT(*) , MAX(CreatedDate)
FROM    dbo.tblTags
GROUP BY Tag

Which outputs the following:

+-----------------+------------------+-------------------------+
|       Tag       | (No column name) |    (No column name)     |
+-----------------+------------------+-------------------------+
| a great tag     |                1 | 2015-04-01 18:30:31.623 |
| not a test      |                1 | 2015-04-01 17:46:09.360 |
| test            |                5 | 2015-04-01 18:13:17.920 |
| test2           |                1 | 2013-03-07 16:53:54.217 |
+-----------------+------------------+-------------------------+

I'm trying to replicate the output of that query using EntityFramework.

I have the following logic which works:

    var GroupedTags = Tags.GroupBy(c => c.Tag)
        .Select(g => new 
        { 
            name = g.Key, 
            count = g.Count(), 
            date = g.OrderByDescending(gt => gt.CreatedDate).FirstOrDefault().CreatedDate 
        })
        .OrderBy(c => c.name);

But takes horribly long to execute compared to the raw SQL query. Any suggestions on how to optimise my approach? It somehow feels wrong.

like image 302
Michael Jefferys Avatar asked Apr 01 '15 19:04

Michael Jefferys


1 Answers

If you want a max, use the Max() Linq method:

var GroupedTags = Tags.GroupBy(c => c.Tag)
    .Select(g => new 
    { 
        name = g.Key, 
        count = g.Count(), 
        date = g.Max(x => x.CreatedDate)
    })
    .OrderBy(c => c.name);
like image 86
DLeh Avatar answered Sep 28 '22 09:09

DLeh