c# - Need help optimizing loop with Linq -


disclaimer: have little experience linq.

one of tasks @ work maintain e commerce web site. yesterday, 1 of our customers started complaining of timeout occur when tried create feed file google. turns out, if user has more 9,000 items put in feed file, our code takes @ least 1 minute execute.

i couldn't find source of problem running debugger, fired profiler (ants) , let thing. found source of our problem, foreach loop contains bit of linq code. here code:

var productmappings = googleproductmappingaccess.getgoogleproductmappingsbyid(context, productid); list<google_category> retcats = new list<google_category>(numcategories); int added = 0;  //this line flagged profiler taking 48.5% of total run time foreach (google_productmapping pm in (from pm in productmappings orderby pm.mappingtype descending select pm)) {     if (pm.googlecategoryid.hasvalue && pm.googlecategoryid > 0)     {         //this line flagged 36% of total time         retcats.add(pm.google_category);     }      else if (pm.googlecategorymappingid.hasvalue && pm.googlecategorymappingid > 0)     {         retcats.add(pm.google_categorymapping.google_category);     }     else     {         continue;     }      if (++added >= numcategories)     {         break;     } } 

do of more experienced devs have ideas? toying trying replace linq sql, unsure if best course of action here (if written linq, there must reason it).

if can filter out results don't want anyway query should faster - using orderby hence these results use processing in query since have evaluated:

 productmappings.where( pm => (pm.googlecategorymappingid.hasvalue                                 && pm.googlecategorymappingid > 0)                               ||(pm.googlecategorymappingid.hasvalue &&                                   pm.googlecategorymappingid > 0)                       )                 .orderby(...) 

also should limit number of results returned query since use numcategories. add

.take(numcategories) 

to query, instead of checking within foreach loop.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

android - layout with fragment and framelayout replaced by another fragment and framelayout -