title: Optimizing a slow LINQ query
body: <p>I have a LINQ query that I am having trouble optimizing and takes about 5.5 seconds to run. I am using a view called StaffingResourceData and a table called StaffingForecasts. </p>
  
  <p>Each StaffingResource has a ResourceId, a Division, and a Type. A StaffingForecast has a ResourceId, Project, Date (represents a Monday of a week), Hours. A StaffingResource can have 0-many StaffingForecasts. </p>
  
  <p>For each StaffingResource, I need a list of their total forecasted hours for the next 12 weeks. Here is what I have right now:</p>
  
  <pre><code>// Get list of dates
  var dates = new List&lt;DateTime&gt;();
  var start = Utilities.GetStartOfWeek(DateTime.Today);
  for (var i = 0; i &lt; 12; i++)
  {
      dates.Add(start.AddDays(i * 7));
  }
  var end = dates[11];
  
  // Get resources
  var resources = (from r in context.StaffingResourceDatas
                   where r.EmployeeId != null
                       &amp;&amp; !exclusionList.Contains(r.ResourceTitleId)
                   join f in context.StaffingForecasts.Where(x =&gt; x.Date &gt;= start &amp;&amp; x.Date &lt;= end) on r.ResourceId equals f.ResourceId into g1
                   from f in g1.DefaultIfEmpty()
                   group new { f.Date, f.Hours } by r into g2
                   select new ChartResourceModel
                   {
                       ResourceId = g2.Key.ResourceId,
                       Division = g2.Key.ResourceDivision,
                       Type = g2.Key.ResourceType,
                       Dates = dates.Select(d =&gt; new ChartDateModel
                       {
                           Date = d,
                           Available = (g2.Where(f =&gt; f.Date == d).Any() ? g2.Where(f =&gt; f.Date == d).Sum(f =&gt; f.Hours) : 0) &lt; 24
                       }).ToList()
                   })
                 .ToList();
  </code></pre>
  
  <p>Any ideas on how I could speed this up?</p>