2013-08-25 107 views
1

我試圖創建用戶頁面,它會顯示,如果用戶最近很喜歡的東西,創建項目在飼料事件的有序飼料,評論後等我將如何做到這一點?我正在考慮從我的數據庫中獲取不同信息的對象列表,然後按日期排序,但我無法獲得正確排序的代碼。按日期創建

回答

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)); 
+1

不要忘記在最後添加一個'userFeed = userFeed.OrderByDescending(feed => feed.Date)'來獲取整個列表的排序順序,除非您想要一個收藏夾後跟一個評論塊等。 –

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 
     }) 
    ); 

添加更多的毗連報表可以根據需要,只要他們被投射到相同的結構(無論是匿名或實際的類),你可以將它們合併成一個列表。

如果你不喜歡有一個巨大的語句,有一個類來存儲項目(例如Feed),然後選擇第一個,做.ToList(),那麼你將有一個List<Feed>,您可以調用.AddRange(linqQueryThatReturnsFeedItems)每加一套您想要包含的項目。

只是有點每個列表,並提供額外的過濾器。一旦你將它們合併成一個,你就可以對合並的列表進行排序。

+0

我試圖做線沿線的東西:http://pastebin.com/4WRYXntJ但我得到一個'無法從轉換' System.Linq.IQueryable '到'System.Linq.ParallelQuery '我很確定數據匹配。 –

+1

簡單的解決方案:創建一個類,以及新的它在你的選擇,而不是匿名類,例如'選擇(註釋=>新進{標題= comment.Title,CreatedAt = comment.DatePublished})',那麼你將能夠在無問題Concat的。 –