Summing some datum for requests in each domain that fall in a date range I have a LINQ query which works fine. I am however very interested to understand if this can be written in a more optimum way...

var query = (from r in Results.All.AsEnumerable()
                       where r.RequestType.Id == Id &amp;&amp;
                             r.DateFrom &gt;= sDate &amp;&amp;
                             r.DateTo &lt;= eDate
                       group r by new {r.Data_1} into g
                       select new {data = g.Key.Data_1, 
                                    sum = g.Sum(s =&gt; int.Parse(s.Data_2))}).ToList();


I am trying to sum Data_2 (stored as a string) by a unique list of Data_1 all by a given date range.

I have provided some sample data below:

 

For example: facebook.com = 51, m.facebook.com = 94 etc.
This is a case where a foreach loop might work better.  Your LINQ query iterates for your data several times.  Where as a foreach loop and a dictionary, should be able to accomplish this in one loop.  Something like this:

Dictionary&lt;string,int&gt; query = new Dictionary&lt;string, int&gt;();
foreach(var r in Results)
{
    if(r.RequestType.Id == Id &amp;&amp; r.DateFrom &gt;= sDate &amp;&amp; r.DateTo &lt;= eDate)
    {
         if(query.ContainsKey(r.Data_1))
         {
             query[r.Data_1] += int.Parse(r.Data_2);
         }
         else
         {
             query.Add(r.Data_1, int.Parse(r.Data_2));
         }
    }
}


While there is a Dictionary lookup for each item it should be more than offset by calculating the sum on the fly rather than at the end.