Pavan Kamath
Pavan Kamath

Reputation: 23

Linq to format a list of items to replace foreach loop

I have got a single list of items which has all the comments and reply's to a post. I would like to format it depending on comments and reply's together by comparing CommentID to ReplyToCommentId.

here is what im using foreach loop to get result which i would like to replace with 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);
        }
      }
    }

Is this possible in LINQ.

Thanks in advance.

Upvotes: 2

Views: 282

Answers (1)

SLaks
SLaks

Reputation: 887797

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

Or

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

You can make it faster (O(n) rather than O(n2)) by replacing the nested Where calls with a pre-computed ToLookup(r => r.ReplyToCommentId)

Upvotes: 1

Related Questions