猿问

如何动态指定Linq OrderBy参数?

如何orderby使用我作为参数的值指定传递给参数的参数?


例如:


List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}

目前执行:


List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();

而不是c.Address,我如何将其作为参数?



 string param = "City";

 List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();


杨魅力
浏览 804回答 3
3回答

猛跑小猪

这是使用反射的可能性...var param = "Address";&nbsp; &nbsp;&nbsp;var propertyInfo = typeof(Student).GetProperty(param);&nbsp; &nbsp;&nbsp;var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null));
随时随地看视频慕课网APP
我要回答