我有两个实体:
博客:
public int Id { get; set; }
public string Name { get; set; }
public List<Post> Posts { get; set; }
帖子:
public int Id { get; set; }
public string Name { get; set; }
public DateTime Published { get; set; }
...我有两个 View 模型:
BlogVm:
public int Id { get; set; }
public string Name { get; set; }
public List<PostVm> Posts { get; set; }
PostVm:
public int Id { get; set; }
public string Name { get; set; }
public DateTime Published { get; set; }
如您所见,它们是相同的。
我只想获取至少包含至少 3 个帖子的博客,并且仅获取3 个最新帖子。此外,我想OrderByDescending Post.Published。
对于映射,我使用 AutoMapper。
我正在尝试类似的方法,但是代码没有按我的预期工作。
var blogs = _context.Blogs.Include(x => x.Posts)
.Where(x.Posts.Count >= 4)
.ProjectTo<BlogVm>()
.OrderByDescending(x => x.Posts.OrderByDescending(y => y.Published)).ToList();
我收到一条错误消息:
"System.ArgumentException: 'At least one object must implement IComparable.'"
最佳答案
目前,您要求它按每个博客的有序帖子对博客进行排序,这...没有意义。您也许可以按博客
的最近发布日期对它们进行排序,并单独对每个博客
的.Posts
按发布日期降序排列?
var blogs = _context.Blogs.Include(x => x.Posts)
.Where(x.Posts.Count >= 4)
.ProjectTo<BlogVm>()
.OrderByDescending(x => x.Posts.Max(y => y.Published)).ToList();
foreach(var blog in blogs) {
blog.Posts.Sort((x,y) => y.Published.CompareTo(x.Published));
}
关于c# - 按子元素排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941983/