1

我想按最后评论日期或帖子日期订购帖子列表。

这是课程:

public class Post
{    
    public int Id { get; set; }
    public string Text { get; set; }
    public System.DateTime DatePosted { get; set; }
    public ICollection<Comment> Comments { get; set; }
}

public partial class Comment
{
    public int Id { get; set; }
    public int PostId { get; set; }
    public string Text { get; set; }
    public System.DateTime DateCommented { get; set; }
}

理想的代码(甚至不编译)将是:

IEnumerable <Post> posts = MVPMetroEntities.Posts
                                               .OrderByDescending(p => 
                                                       p.DatePosted || p.Comments.Max(c=>c.DateCommented));

有任何想法吗 ?谢谢

4

4 回答 4

2

我假设您正在寻找ThenByDescending

IEnumerable<Post> posts = MVPMetroEntities.Posts
    .OrderByDescending(p => p.DatePosted)
    .ThenByDescending(p => p.Comments.Max(c => c.DateCommented));
于 2013-01-18T11:16:56.183 回答
1
var posts = MVPMetroEntities.Posts
                .Select(p => new { 
                     Date = p.Comments.Any() 
                                ? p.Comments.OrderByDescending(c => c.DateCommented).First().Date 
                                : p.DatePosted, 
                     Post = p
                  }
                .OrderByDescending(x => x.Date);
于 2013-01-18T11:29:03.227 回答
0

我没有清楚地理解你的意图,但是这个怎么样

MVPMetroEntities.Posts
.OrderByDescending(p => Recent(p.DatePosted, p.Comments.Max(c => c.DateCommented)));

通过使用这样的辅助方法/扩展方法

        public DateTime Recent(DateTime dt1, DateTime dt2)
        {
            return dt1 > dt2 ? dt1 : dt2;
        }

注意:如果您使用任何 ORM(如 Linq-to-sql),助手可能无法工作

于 2013-01-18T11:26:08.490 回答
0

我通过在 OrderByDescending 中使用三元运算符找到了答案。谢谢 :)

MVPMetroEntities.Posts
            .OrderByDescending(
                    e => e.Comments.Any() ? e.Comments.Max(f => f.DateCommented) : e.DatePosted)
于 2013-01-18T13:05:37.457 回答