Entity Framework select one of each group by date

后端 未结 4 1171
暖寄归人
暖寄归人 2020-11-30 07:37

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

+----+--------------------------+-------+------------+
| id |         content          | type  |    date    |
+         


        
相关标签:
4条回答
  • 2020-11-30 07:45

    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

    0 讨论(0)
  • 2020-11-30 07:47

    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);
    
    0 讨论(0)
  • 2020-11-30 07:55

    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
    }
    
    0 讨论(0)
  • 2020-11-30 08:01

    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()
                       )
    
    0 讨论(0)
提交回复
热议问题