I've written this to accomplish a specific problem, but it's too long. I've sure that it can be reduce too fit it.
I have the following model:
public class ColumnChart
{
public virtual string type { get; set; }
public virtual string name { get; set; }
public virtual List<double> data { get; set; }
}
- The idea of
List<double>
is to keep 12 values (1 per month if exists) - All these 12 values has to belong someone, so the
name
will keep the legend. - The type is
column
(not always, but in this case will make it simple).
Big Logic
// Create a List of ColumnChart's
var list = new List<ColumnChart>();
// Instantiate one object of type ColumnChart
var serie = new ColumnChart();
// Instantiate the List<double> (like my model says)
serie.data = new List<double>();
// Control the loop
int i = 0;
foreach (var element in MyDataSource)
{
// If the serie.name don't have the current Group Name that came from my DataSource
if (serie.name != element.GroupName)
{
// Isn't the first loop ?
if (i != 0)
{
// Return a new empty instance of ChartColumn
serie = NewInstance();
// Set the legend that belong all data
serie.name = element.GroupName;
// Set the type of the chart
serie.type = "column";
// Instantiate a new List<double> (like my model says)
serie.data = new List<double>();
if (serie.data.Count == element.Month - 1)
{
serie.data.Insert(element.Month - 1, element.ValueRevenue);
}
// If the number of elements in my List<double> is lower then the Month.
else
{
while (serie.data.Count < element.Month - 1)
{
serie.data.Add(0);
}
serie.data.Insert(element.Month - 1, element.ValueRevenue);
}
}
// Is the first loop interaction
else
{
serie.name = element.GroupName;
serie.type = "column";
serie.data.Insert(element.Month - 1, elemento.ValueRevenue);
i++;
}
}
// The serie.name have the same current Group Name that came from my DataSource
else
{
serie.data.Insert(element.Month - 1, element.ValueRevenue);
i++;
}
// My i variable that control the loop is the last interaction ?
if (i == MyDataSource.Count() - 1)
{
list.Add(serie);
}
}
i = 0;
Data Source
MyDataSource [0] Month: 1 GroupName: 'Music' ValueRevenue: 700.0 [1] Month: 2 GroupName: 'Music' ValueRevenue: 700.0 [2] Month: 3 GroupName: 'Music' ValueRevenue: 700.0 [3] Month: 4 GroupName: 'Music' ValueRevenue: 700.0 [4] Month: 5 GroupName: 'Music' ValueRevenue: 700.0 [5] Month: 6 GroupName: 'Music' ValueRevenue: 700.0 [6] Month: 7 GroupName: 'Music' ValueRevenue: 700.0 [7] Month: 8 GroupName: 'Music' ValueRevenue: 700.0 [8] Month: 9 GroupName: 'Car' ValueRevenue: 700.0