LINQ查询中的OrderBy方法允许高效地对数据进行排序。但是,如果您想根据参数动态指定排序参数,该怎么办呢?本文将指导您完成此操作。
假设您有一个Student对象的列表,并希望按其Address属性对其进行排序:
List<Student> existingStudents = new List<Student> { new Student {...}, new Student {...} }; List<Student> orderbyAddress = existingStudents.OrderBy(c => c.Address).ToList();
但是,这将地址排序硬编码了。
要动态指定排序参数,您可以利用反射来构造表达式树:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string orderByProperty, bool desc) { // ... (此处应提供答案中的代码片段) }
您现在可以使用带有动态参数的OrderBy扩展方法:
string param = "City"; List<Student> orderbyCity = existingStudents.OrderBy("City", true).ToList(); // 降序排序
这种方法提供了在运行时指定排序参数的灵活性,允许在LINQ查询中进行可定制和动态的排序。
以上是如何使用参数在 LINQ 中动态排序数据?的详细内容。更多信息请关注PHP中文网其他相关文章!