使用LINQ对字典中的键和值进行排序
本文关键字:键和值 排序 LINQ 字典 使用 | 更新日期: 2023-09-27 17:59:09
我刚刚写了一些代码,将数据添加到这个字典中:
Dictionary<string, Dictionary<string, double>> studentsExamsMarks =
new Dictionary<string, Dictionary<string, double>>();
studentsExamsMarks.Add("Peter", new Dictionary<string, double>());
studentsExamsMarks["Peter"].Add("History", 5.15);
studentsExamsMarks["Peter"].Add("Biology", 4.20);
studentsExamsMarks["Peter"].Add("Physics", 4.65);
studentsExamsMarks.Add("John", new Dictionary<string, double>());
studentsExamsMarks["John"].Add("History", 6.00);
studentsExamsMarks["John"].Add("Biology", 3.75);
studentsExamsMarks["John"].Add("Physics", 4.15);
studentsExamsMarks.Add("Michael", new Dictionary<string, double>());
studentsExamsMarks["Michael"].Add("History", 3.00);
studentsExamsMarks["Michael"].Add("Biology", 3.95);
studentsExamsMarks["Michael"].Add("Physics", 4.95);
我应该如何首先按照学生的名字(升序)排序和打印,而不是按照内部词典中的双精度值或主题的名字排序和打印?如果你给我看两个版本,我将不胜感激。非常感谢。
您可以使用SelectMany
获取所有内部字典条目,以创建具有所有属性的匿名类型。则OrderBy
和ThenBy
:的排序很简单
var ordered = studentsExamsMarks
.SelectMany(kv => kv.Value
.Select(kvInner => new {Name = kv.Key, Subject = kvInner.Key, Value = kvInner.Value}))
.OrderBy(x => x.Name)
.ThenBy(x => x.Value); // use x.Subject if you want to order by that instead
foreach (var x in ordered)
Console.WriteLine($"{x.Name} {x.Subject} {x.Value}");