33

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

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

Some text | TypeA 
A dog     | TypeB

我已经尝试了一些东西,但没有必要指出无效的表达方式。

4

4 回答 4

71

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

var query = Posts.GroupBy(p => p.Type)
                  .Select(g => g.OrderByDescending(p => p.Date)
                                .FirstOrDefault()
                   )
于 2013-04-29T09:13:08.957 回答
2

我想您可以按类型对您的帖子行进行分组,然后从该类型的日期集合中降序选择第一个内容

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
}
于 2013-04-29T07:46:50.227 回答
2

或使用临时结果和谓词

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);
于 2013-04-29T07:49:04.570 回答
1

从记忆中,这样的事情应该可以做到

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

这会给你一个新的匿名类型,但你总是可以将它映射到一个类

于 2013-04-29T07:59:36.230 回答