HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Summing some datum for requests in each domain that fall in a date range

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
eachsummingrangedatethatforsomedatumfalldomain

Problem

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 &&
                             r.DateFrom >= sDate &&
                             r.DateTo  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.

Solution

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 query = new Dictionary();
foreach(var r in Results)
{
    if(r.RequestType.Id == Id && r.DateFrom >= sDate && r.DateTo <= 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.

Code Snippets

Dictionary<string,int> query = new Dictionary<string, int>();
foreach(var r in Results)
{
    if(r.RequestType.Id == Id && r.DateFrom >= sDate && r.DateTo <= 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));
         }
    }
}

Context

StackExchange Code Review Q#67442, answer score: 3

Revisions (0)

No revisions yet.