具有重复键的KeyValuePair

本文关键字:KeyValuePair | 更新日期: 2023-09-27 18:21:50

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

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

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

但由于我将获得5个最高年龄值,我需要对年龄列表进行排序。如果那样做,我将输掉两个名单之间的比赛。

我尝试将数据存储在SortedDictionary中,其中Key是年龄,Value是日期。问题是它不允许重复按键。在我的情况下,我需要重复按键,因为多个年龄可以相同,日期也可以相同。

有办法解决这个问题吗?

我的代码试图用字典存储。当它存储重复的密钥时,它会抛出一个异常。

//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); 

具有重复键的KeyValuePair

// 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<> s

您应该真正创建具体的类型,因为您将向某种控件提供该类型。

public class PersonAgeDateItem
{
    public string Age {get;set;} // should be an int though..
    public DateTime Date {get;set;}
}

Lambda版本的数据获取;

请注意,我在这里使用匿名object实例,然后稍后执行SelectPersonAgeDateItem。此实现不受益于拥有匿名对象实例,但如果您最终添加了GroupBy Distinct,则在对象比较的形式中有一些好处考虑(而不是在PersonAgeDateItemoverriding GetHashCodeObject.Equals上实现IEqualityComparer<T>)。。。或者任何类似的情况。。。

var data = db.Person.Select(person => new { Age = person.Age, Date = person.Date })
                    .OrderByDescending(person => person.Age)
                    .Take(5)
                    .Select(person => new PersonAgeDateItem() {
                        Age = person.Age,
                        Date = person.Date
                    });
// person.Age, being a string, could pose an issue.. like "2" coming after "19", "199", "1999".. etc etc

然后,我们对xValueyValue初始化执行另一个Select

...
ageChart.AddSeries( 
    chartType: "column", 
    xValue: data.Select(person => person.Age), 
    yValues: data.Select(person => person.Date));

您可以使用List<Tuple<double, DateTime>>来保存您的年龄和日期列表,而不是Dictionary

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();