首页 > 解决方案 > 基于 Dictionary Key-Value 的 List 中的 OrderBy

问题描述

我有以下列表:

List<Student> list = 
[
  {
    "id": 1,
    "name": "Student 1",
    "OtherInformation": {
      "hobby": "Music",
      "Score": 50
    }
  },
  {
    "id": 2,
    "name": "Student 2",
    "OtherInformation": {
      "hobby": "Golf",
      "Score": 70
    }
  },
  {
    "id": 3,
    "name": "Student 3",
    "OtherInformation": {
      "hobby": "Archery",
      "Score": 30
    }
  }
]

Other Information是一个字典,我需要OrderBy使用字典值的完整列表,这将是动态的,即存储在某个变量中。

var sortKey = "id";
var propertyInfo = typeof(Student).GetProperty(sortKey);
list = list.OrderBy(x => propertyInfo.GetValue(x, null)).ToList();

我无法为字典键值执行上述解决方案,例如Score

学生.cs

 public class Student
{
 public string Id {get;set;}
 public string Name {get;set;}
 public IDictionary<string, object> OtherInfomration{get;set;}
}

需要帮助。

标签: c#listlinqdictionarykey-value

解决方案


我想你想这样做:

var sortKey = "OtherInformation";
var propertyInfo = typeof(Student).GetProperty(sortKey);
list = list.OrderBy(x => ((IDictionary<string, object>)propertyInfo.GetValue(x, null))["Score"]).ToList();

但是,尚不完全清楚您为什么要使用反射。你可以很容易地做到这一点:

list = list.OrderBy(x => x.OtherInformation["Score"]).ToList();

推荐阅读