如何添加对象列表并将其返回

时间:2016-12-01 09:01:40

标签: c# c#-4.0 c#-3.0

这里我得到的所有帖子和评论都指向friendID它的工作正常,我的问题是当我调试它在GetAllPost中显示我2个或更多数据,但它只返回最后的数据,我不知道它为什么不返回所有数据立刻需要帮助..

 public dynamic getalldetails(int friendsid)
 {
     var GetAllPost = (dynamic)null;
     FriendsId =dbContext.Usertable.where(u=>u.userID==friendsid).tolist();

     if(FriendsId!=null)
     foreach(var item in FriendsId )
     {
         GetAllPost =   (from post in db.Posts.where(item.userID==post.userID).ToList() 
                       orderby post.PostedDate descending
                       select new
                       {
                           Message = post.Message,
                           PostedBy = post.PostedBy,
                           PostedByName = post.UserProfile.UserName,
                           PostedByAvatar =imgFolder + (String.IsNullOrEmpty(post.UserProfile.AvatarExt) ? defaultAvatar : post.PostedBy + "." + post.UserProfile.AvatarExt), 
                           PostedDate = post.PostedDate,
                           PostId = post.PostId,
                           PostComments = from comment in post.PostComments.ToList() 
                                          orderby comment.CommentedDate
                                          select new
                                          {
                                              CommentedBy = comment.CommentedBy,
                                              CommentedByName = comment.UserProfile.UserName,
                                              CommentedByAvatar = imgFolder +(String.IsNullOrEmpty(comment.UserProfile.AvatarExt) ? defaultAvatar :  comment.CommentedBy + "." + comment.UserProfile.AvatarExt), 
                                              CommentedDate = comment.CommentedDate,
                                              CommentId = comment.CommentId,
                                              Message = comment.Message,
                                              PostId = comment.PostId
                                          }
                        }).AsEnumerable(); 

    }
   return GetAllPost;
}

1 个答案:

答案 0 :(得分:0)

每次循环播放时,您都会分配给GetAllPost,从而丢弃之前持有的内容。你需要积累帖子 - 这些内容:

ArrayList GetAllPost = new ArrayList();
...
foreach (var item in FriendsId)
{
    GetAllPost.AddRange(from post in
        // Your LINQ code
        ...);
}

return GetAllPost;