Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ对字典中的键和值进行排序_C#_Linq_Sorting_Dictionary - Fatal编程技术网

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

C# 使用LINQ对字典中的键和值进行排序,c#,linq,sorting,dictionary,C#,Linq,Sorting,Dictionary,我刚刚编写了一些代码,将数据添加到此词典中: Dictionary<string, Dictionary<string, double>> studentsExamsMarks = new Dictionary<string, Dictionary<string, double>>(); studentsExamsMarks.Add("Peter", new Dictionary<string, do

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

    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);
Dictionary studentsExamsMarks=
新字典();
添加(“彼得”,新字典());
学生成绩[“彼得”]加上(“历史”,5.15);
学生成绩[“彼得”]加上(“生物学”,4.20);
学生成绩[“彼得”]加上(“物理学”,4.65);
添加(“John”,新字典());
学生成绩[“约翰”]。加上(“历史”,6.00);
学生成绩[“约翰”]加上(“生物学”,3.75);
学生成绩[“约翰”]。加上(“物理学”,4.15);
添加(“Michael”,新字典());
学生评分[“迈克尔”]。加上(“历史”,3.00);
学生成绩评分[“迈克尔”]。加上(“生物学”,3.95);
学生成绩[“迈克尔”]加上(“物理学”,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}");
请阅读并分享你的研究成果。分组和排序在MSDN、web和本网站上有大量的文档记录。