实体框架选择每个组的一个日期 [英] Entity Framework select one of each group by date

查看:81
本文介绍了实体框架选择每个组的一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的(表名:帖子):表

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 |
+----+--------------------------+-------+------------+

使用LINQ表达我想找到每一个最新的内容类型,所以结果应该是

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.

推荐答案

如果你想获得整个帖子。你可以试试这个:

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

这篇关于实体框架选择每个组的一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆