请教一个集合排序的问题

ahking 11 11  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.?)
...全文
5515 点赞 收藏 1
写回复
1 条回复
Dogfish 2020年10月29日
使用反射(Reflection)
var dynamicPropFromStr = typeof(Student).GetProperty("First"); 
GetStudents().OrderBy(u=>dynamicPropFromStr.GetValue(u, null))
回复 点赞
发动态
发帖子
C#
创建于2007-09-28

8.4w+

社区成员

64.0w+

社区内容

.NET技术 C#
社区公告
暂无公告