如何添加对象列表和 return 它

how to add list of object and return it

我在这里得到所有 post 并根据 friendID 评论它工作正常,我的问题是当我调试时它在 GetAllPost 中显示 2 个或更多数据但它的 return 只是最后一个数据,我不明白为什么它不 return 一次处理所有数据需要帮助..

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

每次通过循环,您都将分配给 GetAllPost,从而丢弃它之前持有的任何内容。你需要积累帖子——沿着这些方向:

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

return GetAllPost;