简体   繁体   English

实体框架按日期选择每个组之一

[英]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使用 LINQ 表达式我想找到每种类型的最新内容,所以结果应该是

Some text | TypeA 
A dog     | TypeB

I have tried a few things but no point in pointing out non-working expressions.我已经尝试了一些事情,但指出非工作表达式没有意义。

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()
                   )

I suppose you can group your Posts rows by type and then select first content from descending ordered by date collection of that type我想您可以按类型对 Posts 行进行分组,然后从该类型的日期集合降序中选择第一个内容

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
}

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);

From memory, something like this should do it从记忆中,这样的事情应该做

var data = context.Posts.GroupBy(p => p.Type)
                        .Select(g => new { 
                                          Type = g.Key, 
                                          Date = g.OrderByDescending(p => p.Date)
                                                  .FirstOrDefault()
                                         }
               

This would give you a new anonymous type, but you can always map it to a class这会给你一个新的匿名类型,但你总是可以将它映射到一个类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM