我有一個評論表,它有一個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