This is going to be a two part question.
I am trying to build a data structure for use with the Google Charts API (specifically, their data table).
Here is my code as it stands now:
return Json.Encode(
RMAs
.Where(r => r.CreatedDate.Year > DateTime.Now.Year - 4) //Only grab the last 4 years worth of RMAs
.GroupBy(r => new { Problem = r.Problem, Year = r.CreatedDate.Year, Quarter = ((r.CreatedDate.Month) / 3) })
.Select(r => new { Problem = r.Key.Problem, Year = r.Key.Year, Quarter = r.Key.Quarter, Count = r.Count() })
);
This gets me very close. This gets me an array similar to the following:
{"Problem":"It broke!","Year":2012,"Quarter":2,"Count":3},
{"Problem":"It broke!","Year":2012,"Quarter":1,"Count":1}
But, what I want is for the data to be grouped further by the “Problem” property so that the quarter is an array for each problem (this makes the data structure much easier to iterate over). An example of the desired structure:
{"Problem":"It broke!",
{"Year":2012,"Quarter":2,"Count":3},
{"Year":2012,"Quarter":1,"Count":1}
},
{"Problem":"Some other problem",
{"Year":2012,"Quarter":1,"Count":31}
}
The second part of the question: How can I ensure that I have data for each quarter (again, this makes it much easier to iterate over for building the data table with the API), even if a “Problem” did not occur in that quarter? Using the same example as last time:
{"Problem":"It broke!",
{"Year":2012,"Quarter":2,"Count":3},
{"Year":2012,"Quarter":1,"Count":1}
},
{"Problem":"Some other problem",
{"Year":2012,"Quarter":2,"Count":0}
{"Year":2012,"Quarter":1,"Count":31}
}
Add the following to your query:
You have to insert the following before .ToDictionary() above:
I think… try it out 🙂
I would advise against following this approach, however, and create “empty” records on the client, to avoid excessive bandwidth use.