tags:

views:

166

answers:

2

What I have is a set of users with join dates and I want to use GoogleChartSharp to create a chart showing how many users have joined each month.

So I have this set of dates (US format) in a list:

01/01/2009

02/01/2009

02/12/2009

03/02/2009

03/12/2009

03/22/2009

Googlechartsharp requires me to do something like this:

string[] monthYears  = new string[] { "01/2009", "02/2009", "03/2009"};
int[] number= new int[] {1,2,3};

LineChart chart = new LineChart(150, 150);
chart.SetData(data);
chart.SetLegend(monthYears);

string url = chart.GetUrl();

How do I utilize linq to get the list of dates into arrays required by google? Or is Linq even the right tool?

A: 

Asusming those numvers are the number of times each month occurs. Then you could do something like this:

var numbers = from d in monthYears .Select(x => DateTime.Parse(x))
group d by d.Month into dg
select dg.Count();

That will give you an IEnumerable of the count for each. If you need it as an array it is not too hard to convert that to an array.

Matthew Manela
+2  A: 

Sure, Linq is an ideal tool. The code below is an example. (I have specified the month in the dates so I don't have to use DateTime.ParseExact when setting up the input array).

DateTime[] dates =
{
    DateTime.Parse("jan/01/2009")
    ,DateTime.Parse("feb/01/2009")
    ,DateTime.Parse("feb/12/2009")
    ,DateTime.Parse("mar/02/2009")
    ,DateTime.Parse("mar/12/2009")
    ,DateTime.Parse("mar/22/2009")
};

var datesGroupedByMonthYear = from date in dates
                           group date by date.ToString("MM/yyyy") into groupedDates
                           orderby groupedDates.First() ascending
                           select new { MonthYear = groupedDates.Key, Dates = groupedDates };

string[] monthYears = (from d in datesGroupedByMonthYear select d.MonthYear).ToArray();
int[] number = (from d in datesGroupedByMonthYear select d.Dates.Count()).ToArray();
Mark Glasgow
on a perf note, if the list of dates is quite long, it might be better to store the results of the datesGroupedByMonthYear into a list, before running the secondary linq queries to get monthYears and number arrays.
Mark Glasgow