我有一个 Comment 表,它有一个 CommentID 和一个 ParentCommentID。我正在尝试获取评论的所有子项的列表。这是我目前所拥有的,我还没有测试过。
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;
}
}
}
2个问题:
- 有什么明显的方法可以改善这一点吗?(除了可能使用 CTE 在 sql 中创建视图。)
- 为什么我不能
IEnumerable <Comment>
向 IEnumerable屈服<Comment>
,只能向Comment
它自己屈服? - 无论如何在这种情况下使用 SelectMany 吗?