请教一个集合排序的问题

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.?)
...全文
5569 1 打赏 收藏 举报
写回复
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dogfish 2020-10-29
使用反射(Reflection)
var dynamicPropFromStr = typeof(Student).GetProperty("First"); 
GetStudents().OrderBy(u=>dynamicPropFromStr.GetValue(u, null))
  • 打赏
  • 举报
回复
发帖
C#

10.8w+

社区成员

.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
帖子事件
创建了帖子
2020-10-28 10:48
社区公告

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