我想根据帖子的最后评论或日期订购帖子列表。
这是课程:
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));
有什么想法吗?感谢
答案 0 :(得分:2)
我假设您正在寻找ThenByDescending
:
IEnumerable<Post> posts = MVPMetroEntities.Posts
.OrderByDescending(p => p.DatePosted)
.ThenByDescending(p => p.Comments.Max(c => c.DateCommented));
答案 1 :(得分: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);
答案 2 :(得分: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
),帮助程序可能无法正常工作答案 3 :(得分:0)
我在OrderByDescending中使用三元运算符找到了答案。谢谢:))
MVPMetroEntities.Posts
.OrderByDescending(
e => e.Comments.Any() ? e.Comments.Max(f => f.DateCommented) : e.DatePosted)