0

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);
}
user990423
  • 1,397
  • 2
  • 12
  • 32
Trevor_zam
  • 592
  • 2
  • 7
  • 21

1 Answers1

1

SortedDictionary<double, DateTime> represents a collection of key/value pairs that are sorted on the key, which in your case would appear to be Age, which is a double and thus comparable:

var topAgeDict = new SortedDictionary<double, DateTime>();

You can use this instead of Dictionary<double, DateTime>.

Update

Incidentally, keying a dictionary with a floating point number is dangerous, since seemingly innocuous operations such as

can lead to a tiny precision loss and thus a lookup failure due to a failed equality check. For more see Best collection to use with type Double as key.

dbc
  • 104,963
  • 20
  • 228
  • 340