繁体   English   中英

如何添加对象列表并返回它

[英]how to add list of object and return it

在这里,我正在将所有帖子和评论都编码为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;
}

每次循环时,您都将分配给GetAllPost ,从而丢弃之前保存的内容。 您需要积累帖子-类似于以下内容:

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

return GetAllPost;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM