2011-08-16 51 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

對於UpdateQuery,您在Id上匹配AddQuery,在DistributionId上匹配。如果這是一個錯字,並且對於這兩種情況都應該是IdDistributionId,那麼您可以在同一個循環中更有效地處理添加和更新。

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. 
     } 
    }