2012-04-26 3 views
2

私はすべてのコメントと投稿への返信を持つ項目の単一のリストを持っています。 CommentsIDとReplyToCommentIdを比較することで、コメントに応じて書式を設定して返信したいと思います。Linqは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); 
     } 
     } 
    } 

と交換したい結果を得るために、foreachループを使用して何イムある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) 
    ) 

あなたはこれが私の問題を解決し、事前に計算ToLookup(r => r.ReplyToCommentId)

+0

でネストされたWhere呼び出しを置き換えることで、それはより速く(O(n)ではなくO(n2))することができます。どうもありがとう.. –

関連する問題