2011-08-16 4 views
0
  var AddQuery = from newdist in newSpec.Distributions 
       where !(from oldDist in oSpec.Distributions 
       select oldDist.Id).Contains(newdist.Id) 
       select newdist; 

      foreach (var dist in AddQuery) 
      { 
      dist.operation="Add"; 
      } 
      var updateQuery = from oldDistributionForUpdate in ospec.Distributions 
          where (from newDistributionForUpdate in newspec.Distributions 
          select newDistributionForUpdate.DistributionId).Contains(oldDistributionForUpdate.DistributionId) 
          && 
          (from newDistributionForUpdate in newpaymentSpecification.Distributions 
          select newDistributionForUpdate.Amount).Equals(oldDistributionForUpdate.Amount) 
          select oldDistributionForUpdate; 

      foreach (var dist in updateDistQuery) 
      { 
      dist.operation = "Update"; 
      } 

を使用してオブジェクトを反復処理するための最良の方法は何ですか?私は&プロセス彼ら、私がやっている何を達成するための簡単な方法がありますその結果、クエリの両方からオブジェクトのコレクションを持っていることを計画していますLINQ

+0

私はあなたがコレクションを繰り返す方法がそれを行う最も簡単な方法だと思います。あなたは 'AddQuery.ToList()を実行することができます。ForEach(i => i.operation =" Add ")' –

答えて

0

元のスニペットでは、AddQueryIdUpdateQueryDistributionIdと一致しています。これがタイプミスで、どちらの場合もIdまたはDistributionIdである必要がある場合は、同じループでAddとUpdateをはるかに効率的に処理できます。

var AddUpdateQuery = from newdist in newSpec.Distributions 
         join oldDist in oSpec.Distributions 
         on newdist.Id equals oldDist.Id into matchingDistributions 
         select new { newdist, matchingDistributions }; 

    foreach (var dist in AddUpdateQuery) 
    { 
     if (!dist.matchingDistributions.Any()) 
     { 
      dist.newdist.operation = "Add"; 
      //additional processing for "Add" operation. 
     } 
     else if (dist.newdist.Amount == dist.matchingDistributions.First().Amount) 
     { 
      dist.newdist.operation = "Update"; 
      //additional processing for "Update" operation. 
     } 
    }