请教一个集合排序的问题

ahking 2020-10-28 10:48:04

public class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
}

public static List<Student> GetStudents()
{
// Use a collection initializer to create the data source. Note that each element
// in the list contains an inner sequence of scores.
List<Student> students = new List<Student>
{
new Student {First="Svetlana", Last="Omelchenko", ID=111},
new Student {First="Claire", Last="O'Donnell", ID=112},
new Student {First="Sven", Last="Mortensen", ID=113},
new Student {First="Cesar", Last="Garcia", ID=114},
new Student {First="Debra", Last="Garcia", ID=115}
};

return students;

}



GetStudents().OrderBy(u => u.First)
GetStudents().OrderBy(u => u.Last)
GetStudents().OrderBy(u => u.ID)

可以排序,如果被排序的字段是个变量,应该怎么写呢?
如 string field="First";
GetStudents().OrderBy(u => u.?)
...全文
5612 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dogfish 2020-10-29
  • 打赏
  • 举报
回复
使用反射(Reflection)
var dynamicPropFromStr = typeof(Student).GetProperty("First"); 
GetStudents().OrderBy(u=>dynamicPropFromStr.GetValue(u, null))

111,092

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧