Reputation: 384
I would like to order a list of posts by date of last comment or date of the post.
This is the classes :
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; }
}
The ideal code (whitch don't even compile) would be :
IEnumerable <Post> posts = MVPMetroEntities.Posts
.OrderByDescending(p =>
p.DatePosted || p.Comments.Max(c=>c.DateCommented));
Any ideas ? thanks
Upvotes: 1
Views: 229
Reputation: 384
I found the answer, with using ternary operator in the OrderByDescending. Thanks :)
MVPMetroEntities.Posts
.OrderByDescending(
e => e.Comments.Any() ? e.Comments.Max(f => f.DateCommented) : e.DatePosted)
Upvotes: 0
Reputation: 7126
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);
Upvotes: 1
Reputation: 1380
I didn't understand your intention clearly, but how about this
MVPMetroEntities.Posts
.OrderByDescending(p => Recent(p.DatePosted, p.Comments.Max(c => c.DateCommented)));
by using a helper method/extension methods like this
public DateTime Recent(DateTime dt1, DateTime dt2)
{
return dt1 > dt2 ? dt1 : dt2;
}
Note: helper may not work if you are using any ORM like Linq-to-sql
Upvotes: 0
Reputation: 460068
I assume you are looking for ThenByDescending
:
IEnumerable<Post> posts = MVPMetroEntities.Posts
.OrderByDescending(p => p.DatePosted)
.ThenByDescending(p => p.Comments.Max(c => c.DateCommented));
Upvotes: 2