c# - 按子元素排序

标签 c# asp.net .net entity-framework automapper

我有两个实体:

博客:

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/

相关文章:

.net - 如何计算 2 个或更多不超过特定值的值集之间的可能数字的数量?

c# - 组合属性 setter "init and private"(C#9)

c# - 使用 string 和 string[] 时无法重载方法

c# - 转换 Model3DGroup 两次

asp.net - 如何获得干净的 ASP.Net 错误页面?

jquery - 一个网页可以处理两个版本的 jQuery 吗?

c# - 在 Web 用户控件中检查 Shift+Click 或 Ctrl+Click

c# - 指针偏移导致溢出

.net - 在基于声明的应用程序中应用自定义声明

c# - 一次显示 DataAnnotation 和 IValidatableObject 的所有验证错误