我正在进行LINQ查询,以从数据库、年龄和日期获取两个字段中的所有值。我想在图表上显示5个最高年龄的数字。为此,我试图将年龄和日期存储在两个单独的列表中,ageList和dateList。
最初,当将该值与每个列表中的索引进行比较时,与年龄和日期的关系将是正确的。例如:
存储在ageList.ElementAt(0)处的年龄将是dateList.ElementAt(0)上日期的正确值。
但是,由于我将获得5位最高年龄的数字,我需要排序的ageList列表。通过这样做,我将输掉两个名单之间的比赛。
我尝试将数据存储在SortedDictionary中,而不是以年龄为键,而值为日期。问题是它不允许重复密钥。在我的例子中,我需要重复的键,因为多个年龄可以相同,日期也可以相同。
有办法绕过这件事吗?
我的代码试图用字典存储。它将在存储重复密钥时抛出异常。
//Linq query
var xChartData = from x in db.Person
                 select new { x.Age, x.Date };
SortedDictionary<double, DateTime> topAgeDict = new SortedDictionary<double, DateTime>();
//Storing in Dictionary
foreach (var x in xChartData)
{
    topAgeDict.Add(x.Age, x.Date); //Exception caused when repeated values
}
Dictionary<string, string> stringDict = new Dictionary<string, string>();
//store data as string for chart purposes
foreach (var x in topAgeDict)
{
    stringDict.Add(x.Key.ToString(), x.Value.ToString());  
}
List<string> ages = new List<string>();
List<string> dates = new List<string>();
//storing the dictionary key and value in List for element access.
ages = stringDict.Keys.ToList();
dates = stringDict.Values.ToList();
//to store only the top 5 results. This will be the data used in chart.
List<string> topFiveAge = new List<string>();
List<string> topFiveDate = new List<string>();
for (int x=1; x <= 5; x++)
{
    topFiveAge.Add(ages.ElementAt(ages.Count - x));
    topFiveDate.Add(dates.ElementAt(dates.Count - x));
}
//Chart
var topAgefilePath = Server.MapPath("~/Chart_Files/topAge.jpg");
            if (System.IO.File.Exists(topAgefilePath))
            {
                System.IO.File.Delete(topAgefilePath);
            }
            var ageChart = new Chart(580, 400);
            ageChart.AddTitle("Top Age");
            ageChart.AddSeries(
                chartType: "column",
                xValue: topFiveDate,
                yValues: topFiveAge
            );
            ageChart.Save(topAgefilePath); 发布于 2015-11-14 10:43:48
与Dictionary不同,您可以使用List<Tuple<double, DateTime>>来保存您的年龄和日期列表。
var ageAndDate = from x in db.Person
                    select new Tuple<double, DateTime>(x.Age, x.Date);
var topFiveAgeWithdate = ageAndDate.OrderByDescending(t => t.Item1).Take(5).ToList();
List<string> topFiveAge = topFiveAgeWithdate.Select(t => t.Item1.ToString()).ToList();
List<string> topFiveDate = topFiveAgeWithdate.Select(t => t.Item2.ToShortDateString()).ToList();Anonymous Type也可以这样做。
var ageAndDate = from x in persons
                    select new { x.Age, x.Date };
var topFiveAgeWithdate = ageAndDate.OrderByDescending(t => t.Age).Take(5).ToList();
List<string> topFiveAge = topFiveAgeWithdate.Select(t => t.Age.ToString()).ToList();
List<string> topFiveDate = topFiveAgeWithdate.Select(t => t.Date.ToShortDateString()).ToList();https://stackoverflow.com/questions/33707413
复制相似问题