C# 实体框架按日期选择每个组之一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16273485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework select one of each group by date
提问by Todilo
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.
我已经尝试了一些事情,但指出非工作表达式没有意义。
采纳答案by Khanh TO
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()
)
回答by Alex
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
}
回答by maxlego
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);
回答by NinjaNye
From memory, something like this should do it
从记忆中,这样的事情应该做
var data = context.Posts.Group(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
这会给你一个新的匿名类型,但你总是可以将它映射到一个类

