gpt4 book ai didi

c# - 具有重复键的 KeyValuePair

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:48 24 4
gpt4 key购买 nike

我正在执行 LINQ 查询以从数据库、年龄和日期中获取 2 个字段中的所有值。我想在图表上显示 5 个最高年龄的数字。为此,我试图将年龄和日期存储在 2 个单独的列表 ageList 和 dateList 中。

最初,在将每个列表中的值与索引进行比较时,与年龄和日期的关系是正确的。例如:

存储在 ageList.ElementAt(0) 中的年龄将是 dateList.ElementAt(0) 中日期的正确值。

但由于我要获得 5 个最高年龄数字,因此我需要对 ageList 列表进行排序。通过这样做,我将失去 2 个列表之间的匹配。

我尝试将数据存储在 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);

最佳答案

// top 5 oldest persons
var xChartData = (from x in db.Person
order by x.Age descending
select new { x.Age, x.Date })
.Take (5);

而且我认为没有真正的理由将它分成两个 List<>

关于c# - 具有重复键的 KeyValuePair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com