I am querying my database to display the top 5 results of that field(age) in a chart. It is being displayed as expected but I am hard coding the corresponding dates. Instead, I want to query the dates from the database too and display it on the chart.
Since I want to display the top 5 results, I am obtaining the results and sorting them first. I believe this would mess up the position of the date that follows the age field. I was trying to use a Dictionary to store the data instead but unable to sort it and obtain the top 5 results of the key. Can I get some help on how I could sort based on the key of the dictionary and use it to update the chart. Or is there a better way than using a dictionary.
Working code where I hard code the dates:
//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);
Trying to query both Date and Age and store with dictionary and sort.
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);
}