Linq格式化项目列表以替换foreach循环

时间:2012-04-26 12:13:23

标签: linq

我有一个项目列表,其中包含所有评论并回复帖子。 我想根据评论格式化它,并通过比较CommentID和ReplyToCommentId一起回复。

这是我使用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 个答案:

答案 0 :(得分: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)调用,您可以加快速度(Where而不是ToLookup(r => r.ReplyToCommentId)