2012-04-26 53 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