c# - 具有重复键的 KeyValuePair

标签 c# linq dictionary

我正在执行 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/

相关文章:

ios - 如何在 swift 中打印字典值数组

c++ - map 的键可以是数组吗? (映射数组错误)

c# - 如何从人员列表中查询孙辈?

c# - 更新 IEnumerable<XElement> 并将更改保存在 XML 文档中 C#

c# - 将类类型作为参数 c# 传递并与字典一起使用

c# - 如何在图像上绘制带有轮廓的文本?

c# - 如何在 ASP.NET MVC View 中对数据进行分组?

c# - 我在哪里可以找到 .net 4.0 SOS.dll?

c# - 我可以在 C# 中加载应用程序期间捕获丢失的 dll 错误吗?

c# - 应用程序启动触发对 crl.microsoft.com 和 ctldl.windowsupdate.com 的请求