使用LINQ对字典中的键和值进行排序

时间:2016-07-29 13:03:18

标签: c# linq sorting dictionary

我刚写了一些代码,将数据添加到此词典中:

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

我应该如何按学生姓名(升序)排序和打印,而不是按内部词典中的双打值或主题名称排序和打印?如果你给我看两个版本,我将非常感激。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用SelectMany获取所有内部字典条目,以创建包含所有属性的匿名类型。然后使用OrderByThenBy

进行排序很简单
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}");