2012-04-26 22 views
2

我收到了一個包含所有評論和答覆的帖子的項目列表。 我想通過比較CommentID到ReplyToCommentId來根據評論和回覆一起來格式化它。Linq格式化項目列表來替換foreach循環

這裏是用什麼IM foreach循環得到的結果,我想使用LINQ

List<UserComment> comments = GetComments(SomeID).ToList(); 

int i = 0; 
    foreach(var item in comments) { 
    if(item.IsReply == false) { 
     i++; 
     formatedComments.Add(item); 
     foreach(var replys in comments) { 
     if(item.CommentID == replys.ReplyToCommentId) { 
      i++; 
      formatedComments.Add(replys); 
     } 
     } 
    } 

更換這是可能的LINQ。

在此先感謝。

回答

1
from c in comments 
where !c.IsReply 
from r in new[] { c }.Concat(
        comments.Where(r => c.CommentID == r.ReplyToCommentId) 
) 
select r 

或者

comments 
    .Where(c => !c.IsReply) 
    .SelectMany(c => new[] { c }.Concat(
        comments.Where(r => c.CommentID == r.ReplyToCommentId) 
    ) 

你可以使其更快(O(n)而不是O(n2)),通過預先計算ToLookup(r => r.ReplyToCommentId)

+0

這解決了我的問題代替嵌套Where電話。非常感謝.. – 2012-04-26 12:43:31