c# - 基于 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;}
}
需要帮助。
解决方案
我想你想这样做:
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();
推荐阅读
- spring-boot - 如何使用 Spring Boot Kafka 在集群中获取 Kafka 代理?
- javascript - 如何在Javascript中的for循环之间放置空格
- sql - 操作数类型冲突:用 (...) 加密的 numeric(16,5) 与浮点数不兼容
- firebase - 在数组 Firestore 中使用地图的复合查询
- handlebars.js - 在 BigCommerce 中显示子类别的子类别
- azure-devops - Azure DevOps - 如何创建不由标签触发的构建管道
- python-3.x - Python:有没有办法在一个单独的变量达到一个 5 的倍数后给一个变量加 1?
- android - 房间数据库android的问题
- python - NLP 神经网络的递归深度超出/内核死亡连接张量
- python - 有没有办法为 python plotly 热图创建分层轴标签?