我有一张评论表,其中包含评论ID和父评论ID。我试图获取所有评论的子评论列表。这是我目前拥有的,我还没有测试过它。
private List<int> searchedCommentIDs = new List<int>();
// searchedCommentIDs is a list of already yielded comments stored
// so that malformed data does not result in an infinite loop.
public IEnumerable<Comment> GetReplies(int commentID) {
var db = new DataClassesDataContext();
var replies = db.Comments
.Where(c => c.ParentCommentID == commentID
&& !searchedCommentIDs.Contains(commentID));
foreach (Comment reply in replies) {
searchedCommentIDs.Add(CommentID);
yield return reply;
// yield return GetReplies(reply.CommentID)); // type mis-match.
foreach (Comment replyReply in GetReplies(reply.CommentID)) {
yield return replyReply;
}
}
}
两个问题:
- Is there any obvious way to improve this? (Besides maybe creating a view in sql with a CTE.)
- How come I can t yield a
IEnumerable <Comment>
to an IEnumerable<Comment>
, onlyComment
itself? - Is there anyway to use SelectMany in this situation?