1

我正在尝试在用户页面上创建一个提要,如果用户最近喜欢某些东西、创建项目、评论帖子等,它将在该页面上显示。我将如何做到这一点?我正在考虑列出从数据库中获取的不同信息的对象列表,然后按日期排序,但我无法正确排序代码。

4

2 回答 2

1

怎么样:

var feed = db.Likes
    .Where(like => like.UserID == currentUserID)
    .Where(like => like.CreatedAt > createdSince)
    .OrderByDescending(like => like.CreatedAt)
    .Select(like => new {
        Type = "like",
        CreatedAt = like.CreatedAt
    })
    .Concat(db.Comments
        .Where(comment => comment.UserID == currentUserID)
        .Where(comment => comment.CreatedAt > createdSince)
        .OrderByDescending(comment => comment.CreatedAt)
        .Select(comment => new {
            Type = "comment",
            CreatedAt = comment.CreatedAt
        })
    );

根据需要添加更多 Concat 语句,只要它们投影到相同的结构(匿名或实际类),您就可以将它们合并到一个列表中。

如果你不喜欢有一个巨大的声明,并且有一个类来存储项目(例如Feed)然后选择第一个并做.ToList(),那么你将有一个List<Feed>你可以.AddRange(linqQueryThatReturnsFeedItems)为你想要包括的每组额外的项目调用的。

只需对每个列表进行排序并提供额外的过滤器。将它们合并为一个后,您可以对合并的列表进行排序。

于 2013-08-25T23:07:57.620 回答
1

好吧,我最终做的事情是这样的:

public class UserFeed
{
    public string Type { get; set; }
    public int Reference_Id { get; set; }
    public int Comic_Id { get; set; }
    public int Chapter_Id { get; set; }
    public int Page_Id { get; set; }
    public int User_Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public decimal Rating { get; set; }
    public string Image { get; set; }
    public DateTime Date { get; set; }
}

 List<UserFeed> userFeed = new List<UserFeed>();
 userFeed.AddRange(user.SelectMany(i => i.UserFavorites).Select(i => new UserFeed { Type = "UserFavorite", Reference_Id = i.UserFavorite_Id, Comic_Id = i.Comic_Id, Title = i.Comic.Title, Image = i.Comic.ComicImage, Date = i.DateFavorited }).OrderByDescending(i => i.Date).Take(6));
 userFeed.AddRange(Comics.SelectMany(i => i.ComicReviews).Select(i => new UserFeed { Type = "ComicReview", Reference_Id = i.ComicReview_Id, Comic_Id = i.Comic_Id, Title = i.Comic.Title, Text = i.Text, Rating = i.ComicRating.Rating, Image = i.Comic.ComicImage, Date = i.DatePublished }).OrderByDescending(i => i.Date).Take(6));
 userFeed.AddRange(Comics.SelectMany(i => i.Chapters).Select(i => new UserFeed { Type = "Chapter", Reference_Id = i.Chapter_Id, Comic_Id = i.Comic_Id, Title = i.Title, Image = i.Comic.ComicImage, Date = i.DatePublished }).OrderByDescending(i => i.Date).Take(6));
 userFeed.AddRange(Comics.SelectMany(i => i.Chapters.SelectMany(j => j.Pages)).Select(i => new UserFeed { Type = "Page", Reference_Id = i.Page_Id, Chapter_Id = i.Chapter_Id, Title = i.Title, Image = i.PageImage, Date = i.DatePublished }).OrderByDescending(i => i.Date).Take(6));
于 2013-08-26T00:21:33.527 回答