Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 31st, 2012  |  syntax: None  |  size: 0.72 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Linq to format a list of items to replace foreach loop
  2. List<UserComment> comments = GetComments(SomeID).ToList();
  3.  
  4. int i = 0;
  5.   foreach(var item in comments) {
  6.     if(item.IsReply == false) {
  7.       i++;
  8.       formatedComments.Add(item);
  9.       foreach(var replys in comments) {
  10.         if(item.CommentID == replys.ReplyToCommentId) {
  11.           i++;
  12.           formatedComments.Add(replys);
  13.         }
  14.       }
  15.     }
  16.        
  17. from c in comments
  18. where !c.IsReply
  19. from r in new[] { c }.Concat(
  20.                     comments.Where(r => c.CommentID == r.ReplyToCommentId)
  21. )
  22. select r
  23.        
  24. comments
  25.     .Where(c => !c.IsReply)
  26.     .SelectMany(c => new[] { c }.Concat(
  27.                     comments.Where(r => c.CommentID == r.ReplyToCommentId)
  28.     )