Linq 查询从第一个 table 加入两个 tables 和 return 对象 - 使用 PagedList

Linq query to join two tables and return object from first table - PagedList used

我使用Entity framework(代码优先模型) 我有 table Posts(postID | Title | ...) 和 table Comments(commentID | Comment | postID | userID | CommentDate | ...)

我想要一个基于评论中用户 ID 标准的帖子列表。

var listOfPosts = (from p in db.Posts
                    join coment in db.Comments
                    on p.postID equals coment.postID                                
                    where coment.userID == "Some value"
                    orderby coment.CommentDate descending
                    select p).ToList();


return View("ReportList", listOfReports.ToPagedList(pageNumber, pageSize));

我还使用 PagedList 对帖子进行分页。

但我希望结果按 PostID 分组,所以我修改了代码如下

var listOfPosts = (from p in db.Posts
                    join coment in db.Comments
                    on p.postID equals coment.postID
                    where coment.userID == "Some value"
                    orderby coment.CommentDate descending
                    group p by p.postID into newP
                    select newP).ToList();

这里的问题是 PagedList 的第二个查询 returns List<IGrouping<int, Posts>>ToPagedList 方法的结果只适用于 List<Posts>

如何根据评论的条件和顺序将查询更改为 return 不同的帖子列表? 您可以使用 lambda 表达式或查询语法。

您可以尝试在外部查询上使用子查询和 distinct,如下所示:

var listOfPosts = (from b in ((from p in db.Posts
                               join coment in db.Comments on p.postID equals coment.postID
                               where coment.userID == "Some value"
                               orderby coment.ComentDate descending
                               select p).ToList())
                   select b).Distinct().ToList();