linq foreach performance linq foreach performance asp.net asp.net

linq foreach performance


Two immediate suggestions:

  • Don't use p.Methods.Count() > 0 - that needs to perform a full count, even though you only need to know if there are any elements. Use p.Methods.Any() instead.
  • Don't compute this.Project.WorkDaysCount on every iteration. We don't know the details of what's going on there, but it may be expensive. Precompute it, and use the constant.

Here's the improved query code:

int workDaysCount = Project.WorkDaysCount;var x = tt.Where(p => p.Methods.Any() &&                  p.PerWeek != workDaysCount &&                 !p.IsManual);

As others have said, the reason the query construction itself doesn't take any significant time is that's it's not doing any real work. However, knowing that doesn't make it any faster, of course :)

Beyond that, we're going to need to know more about the context. Is this LINQ to Objects, LINQ to SQL, or something else? What's the type of tt?


Linq uses delayed execution. Your linq query doesn't actually execute until someone uses the IEnumerable returned. The execution time you are seeing is the result of the query, not the foreach.


It's deferred execution.write x.ToList(); and it will take ~ 3 seconds too.