Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework select one of each group by date

I have a table like this (Table name: Posts):

+----+--------------------------+-------+------------+
| id |         content          | type  |    date    |
+----+--------------------------+-------+------------+
|  0 | Some text                | TypeA | 2013-04-01 |
|  1 | Some older text          | TypeA | 2012-03-01 |
|  2 | Some even older texttext | TypeA | 2011-01-01 |
|  3 | A dog                    | TypeB | 2013-04-01 |
|  4 | And older dog            | TypeB | 2012-03-01 |
|  5 | An even older dog        | TypeB | 2011-01-01 |
+----+--------------------------+-------+------------+

Using a LINQ expression I want to find the newest content of each type, so the result should be

Some text | TypeA 
A dog     | TypeB

I have tried a few things but no point in pointing out non-working expressions.

like image 600
Todilo Avatar asked Apr 29 '13 07:04

Todilo


3 Answers

If you want to get the whole Posts. You can try this:

var query = Posts.GroupBy(p => p.Type)
                  .Select(g => g.OrderByDescending(p => p.Date)
                                .FirstOrDefault()
                   )
like image 64
Khanh TO Avatar answered Oct 19 '22 21:10

Khanh TO


Or using temporary result and predicate

var tmp = posts.GroupBy(x => x.type).Select(x => new {x.Key, date = x.Max(g => g.date)).ToArray();

var filter = PredicateBuilder.False<Post>();

foreach (var item in tmp)
{
    filter = filter.Or(x => x.type == item.Key && x.date == item.date);
}

var newestPosts = posts.Where(filter);
like image 2
maxlego Avatar answered Oct 19 '22 21:10

maxlego


I suppose you can group your Posts rows by type and then select first content from descending ordered by date collection of that type

from row in Posts 
group row by row.type 
into g
select new
{       
    Content  = (from row2 in g orderby row2.date descending select row2.content).FirstOrDefault(),
    Type = g.Key
}
like image 2
Alex Avatar answered Oct 19 '22 22:10

Alex