private void button1_Click(object sender, EventArgs e)
{
chart1.Series.Clear();
//模拟你的原始数据
var list = new List<Test>(){
new Test{ month = 1, item = "A001", qty = 1200 },
new Test{ month = 2, item = "A001", qty = 1100 },
new Test{ month = 3, item = "A001", qty = 1800 },
new Test{ month = 4, item = "A001", qty = 600 },
new Test{ month = 5, item = "A001", qty = 200 },
new Test{ month = 1, item = "B001", qty = 1000 },
new Test{ month = 2, item = "B001", qty = 1500 },
new Test{ month = 3, item = "B001", qty = 100 },
new Test{ month = 4, item = "B001", qty = 900 },
new Test{ month = 5, item = "B001", qty = 900 },
new Test{ month = 1, item = "C001", qty = 2000 },
new Test{ month = 2, item = "C001", qty = 1800 },
new Test{ month = 6, item = "C001", qty = 2500 }
};
DataTable dt = ToDataTable(list); //把你的SQL语句结果替换掉ToDataTable(list)
DataTable dtConvert = ConvertDataTable(dt);
var allSeries = dt.AsEnumerable().Select(a => a["item"]).Distinct();
foreach (var item in allSeries)
{
Series series = new Series(item.ToString());
chart1.Series.Add(series);
}
for (int i = 0; i < allSeries.Count(); i++)
{
chart1.Series[i].YValueMembers = chart1.Series[i].Name;
chart1.Series[i].XValueMember = "month";
}
chart1.DataSource = dtConvert;
chart1.DataBind();
}
static DataTable ConvertDataTable(DataTable source)
{
DataTable dt = new DataTable();
dt.Columns.Add("month");
var columns = (from x in source.Rows.Cast<DataRow>() select x[1].ToString()).Distinct();
foreach (var item in columns) dt.Columns.Add(item);
var data = from x in source.Rows.Cast<DataRow>()
group x by x[0] into g
select new { Key = g.Key.ToString(), Items = g };
data.ToList().ForEach(x =>
{
string[] array = new string[dt.Columns.Count];
array[0] = x.Key;
for (int i = 1; i < dt.Columns.Count; i++)
array[i] = (from y in x.Items
where y[1].ToString() == dt.Columns[i].ToString()
select y[2].ToString())
.SingleOrDefault();
dt.Rows.Add(array);
});
return dt;
}