Search code examples
c#linqstopwatch

How to measure the time for LINQ Query?


I tried to use the stopwatch before the linq query and stop it after the LINQ query but the time the linq query takes 2 minutes but the stopwtach result gives 40 MS !!

this is the LINQ Query

Stopwatch stopwatch = Stopwatch.StartNew();
  var sets =
   from a in patient
   from b in patient
   from c in patient
   from d in patient
   from l in patient
   where a.VisitNum < b.VisitNum && b.VisitNum < c.VisitNum && c.VisitNum < d.VisitNum && d.VisitNum < l.VisitNum
   select new { a, b, c, d, l };
                stopwatch.Stop();

any suggestion ?


Solution

  • LINQ uses deferred execution.
    The query does not execute at all until you enumerate the results.

    To force the query to execute, you can call .Count().