Reputation: 9
i would like to count the number of new users in one month. However this is the output i am receiving. How do i go about grouping the repeated months into just "Jan", "Nov". Thank you so much for your help.
public ActionResult UserPerMonth()
{
var _con = new DBEntities();
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
var results = (from c in _con.Users select c);
results.ToList().ForEach(rs => yValue.Add(rs.id.ToString().Count()));
results.ToList().ForEach(rs => xValue.Add(rs.date.Value.ToString("MMM-yyyy")));
var chart = new Chart(width: 300, height: 200)
.AddTitle("Users per month")
.AddLegend()
.AddSeries(
chartType: "Column",
xValue: xValue,
yValues: yValue)
.GetBytes("png");
return File(chart, "image/png");
}
Upvotes: 0
Views: 1085
Reputation: 2256
There may be a more concise way of doing it but this is working for me. Add a class for your Chart Data e.g.
public class ChartData
{
public string Month { get; set; }
public int Count { get; set; }
}
Then you can use a linq query with groupby and count to get the data and put it in to the ChartData type, then move these values to the relevant axis:
public ActionResult UserPerMonth()
{
var _con = new DBEntities();
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
var results = (from c in _con.Users select c);
var axis = results.GroupBy(r => r.date.Value.ToString("MMM-yyyy"))
.Select(r => new ChartData
{
Month = r.Key,
Count = r.Count()
}).ToList();
foreach (var item in axis)
{
xValue.Add(item.Month);
yValue.Add(item.Count);
}
var chart = new Chart(width: 300, height: 200)
.AddTitle("Users per month")
.AddLegend()
.AddSeries(
chartType: "Column",
xValue: xValue,
yValues: yValue)
.GetBytes("png");
return File(chart, "image/png");
}
Upvotes: 1