0

我是 NHibernate 和 LINQ 的新手。我有一段我认为可以优化的代码。请帮我这样做。

 foreach (var geography in geographyList.OrderBy(x => x.Name))
 {

     var introductionDateDetail = environment.IntroductionDateInfo
                                      .IntroductionDateDetails
                                      .OrderByDescending(x => x.ApplicationDate)
                                      .FirstOrDefault(x => x.Geography.Id == geography.Id && 
                                                           x.VaccineDetail.Id == vaccineDetail.Id &&
                                                           x.MasterForecastInfo.Id == masterforecast.Id && 
                                                           x.ViewInfo.Id == viewInfoDetail.ViewInfo.Id);

}

for 循环可能会迭代到大约一千条记录。因此 LINQ 语句也执行了很多次。我们可以编写一段代码来只执行一次 LINQ 语句吗?

4

1 回答 1

0

你可以尝试这样的事情:

var geographiesId = geographyList.Select(g => g.Id);
var introductionDetails = environment.IntroductionDateInfo
                                  .IntroductionDateDetails
                                  .OrderByDescending(x => x.ApplicationDate)
                                  .FirstOrDefault(x => geographiesId.Contains(x.Geography.Id) && 
                                                       x.VaccineDetail.Id == vaccineDetail.Id &&
                                                       x.MasterForecastInfo.Id == masterforecast.Id && 
                                                       x.ViewInfo.Id == viewInfoDetail
于 2013-05-15T13:08:31.773 回答