c# - Need to optimize LINQ code using Nhibernate -


i 'm new nhibernate & linq. have piece of code think can optimized. please me so.

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

the loop may iterate thousand records.and hence linq statement executed many times. can write piece of code can execute linq statement once?

you can try this:

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 

Comments