首页 > 解决方案 > 按嵌套字典值排序?

问题描述

var userInformation = new Dictionary<string, Dictionary<string, int>>();

我需要一个等于这个字典的新字典,但首先按键排序,然后按值的值排序。我试过了:

var resultInformation = userInformation.OrderBy(k => k.Key).ThenBy(v => v.Value.OrderByDescending(x => x.Value));

我尝试了其他几种方法,但没有效果。

标签: c#dictionary

解决方案


字典没有排序,但您可以轻松地生成字典中项目的列表/集合,如下所示:

var resultInformation = from outer in userInformation
                        from inner in outer.Value
                        let data = new { Outer = outer.Key, Inner = inner.Key, Value = inner.Value }
                        orderby data.Outer, data.Inner, data.Value
                        select data;

或等效的查询语法:

var resultInformation = userInformation
    .SelectMany(i => i.Value, (key, inner) => new { Outer = key, Inner = inner.Key, Value = inner.Value})
    .OrderBy(e => e.Outer)
    .ThenBy(e => e.Inner)
    .ThenBy(e => e.Value);

更新:根据您的澄清评论,我认为您真正想要的是更像这样的东西:

var resultInformation = 
    from student in userInformation
    orderby student.Key
    select new
    {
        studentId = student.Key,
        courses = 
            from courseScore in student.Value
            orderby courseScore.Value descending
            select new {
                course = courseScore.Key,
                score = courseScore.Value
            }
    };

推荐阅读