使用linq迭代对象的最佳方法是什么?

时间:2011-08-16 19:39:17

标签: c# linq-to-objects

           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";
          }

我计划从查询结果中获得一组对象。处理它们,有没有更简单的方法来实现我的目标?

1 个答案:

答案 0 :(得分:0)

在原始代码段中,您在Id上与AddQuery匹配,DistributionIdUpdateQuery匹配。如果这是一个拼写错误,两种情况都应该是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.
        }
    }