Entity Framework Group By with Max Date and count

c# entity-framework linq sql

Question

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.

1
7
4/1/2015 7:47:06 PM

Accepted Answer

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);
14
4/1/2015 7:55:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow