mskuratowski
mskuratowski

Reputation: 4124

Order by child property in list

I have an two tables - blog and posts (one to many relationship).

I would like to get all blogs with minimum 3 and take only 3 posts for blog and order list by post publish date.

What I was trying:

_context.Blogs.Where(x => x.IsActive && x.Posts.Count >= 3).OrderByDescending(p => p.Posts.OrderByDescending(x => x.PublishDate)).ToList();

but I'm getting an error message:

ArgumentException: At least one object must implement IComparable.

UPDATE:

Okay, I see it'll be problem to sort by post publish date. I have also in Blog table LastBuildDate property. So how can I order by LastBuildDate?

Upvotes: 1

Views: 2537

Answers (2)

Deetz
Deetz

Reputation: 328

Try this, I haven't tested it.

_context.Blogs.Where(x => x.IsActive && x.Posts.Count >= 3).OrderByDescending(x => x.LastBuildDate).ToList();

Upvotes: 0

Brian Mains
Brian Mains

Reputation: 50728

The nested ordering is throwing off this:

.OrderByDescending(p => p.Posts.OrderByDescending(x => x.PublishDate))

The outer order is evaluating a object that the Posts property is, which doesn't implements IComparable. For instance, if you did:

.OrderByDescending(p => p.Posts.Max(x => x.PublishDate))

Max returns a DateTime. However, OrderbyDescending on posts returns something it can't evaluate here...

Upvotes: 3

Related Questions