我有一个评论表,它有一个CommentID和一个ParentCommentID。我正在尝试获得评论的所有孩子的名单。这是我到目前为止,我还没有测试过。Linq-to-Sql:递归地获取子女
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?
这是LINQ到SQL或LINQ到实体? – bendewey 2009-02-11 04:35:37