我正在查詢我的數據庫以在圖表中顯示該字段(年齡)的前5個結果。它如預期顯示,但我很難編碼相應的日期。相反,我想查詢數據庫中的日期,並將其顯示在圖表上。將數據庫數據存儲在字典中以在圖表上顯示
由於我想顯示前5個結果,我正在獲取結果並對它們進行排序。我相信這會弄亂跟隨年齡段日期的位置。我試圖用字典來存儲數據,但無法對其進行排序並獲得密鑰的前5個結果。我可以根據字典的關鍵字對其進行排序,並使用它來更新圖表。或者有沒有比使用字典更好的方法。
工作代碼,我硬編碼的日期:
//Query to dB and storing it in a list
PersonContext db = new PersonContext();
var xChartData = from x in db.Person
select x.Age;
List<double> topAge = new List<double>();
List<string> topFive = new List<string>();
foreach (var x in xChartData)
{
topAge.Add(x);
}
topAge.Sort();
for (int x = 1; x <= 5; x++)
{
topFive.Add(topAge.ElementAt(topAge.Count - x).ToString());
}
//Chart
var topAgefilePath = Server.MapPath("~/Chart_Files/topAge.jpg");
if (File.Exists(topAgefilePath))
{
File.Delete(topAgefilePath);
}
var myChart = new Chart(580, 400);
myChart.AddTitle("Top Age");
myChart.AddSeries(
chartType: "column",
xValue: new[] { "Date 1", "Date 2", "Date 3", "Date 4", "Date 5" },
yValues: topFive
);
myChart.Save(topAgefilePath);
試圖查詢日期和年齡,並與字典和排序存儲。
var xChartData = from x in db.Person
select new { x.Age, x.Date };
Dictionary<double, DateTime> topAgeDict = new Dictionary<double, DateTime>();
foreach (var x in xChartData)
{
topAgeDict.Add(x.Age, x.Date);
}
@Trevor_zam - 已更新答案 – dbc