LINQ中的动态排序
使用Linq动态属性排序
使用反射:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static Func<T,Tkey> DynamicLambda<T, Tkey>(string propertyName)
{
ParameterExpression p = Expression.Parameter(typeof(T), "p");
Expression body = Expression.Property(p, typeof(T).GetProperty(propertyName));
var lambda = Expression.Lambda<Func<T, Tkey>>(body, p);
return lambda.Compile();
}
{
ParameterExpression p = Expression.Parameter(typeof(T), "p");
Expression body = Expression.Property(p, typeof(T).GetProperty(propertyName));
var lambda = Expression.Lambda<Func<T, Tkey>>(body, p);
return lambda.Compile();
}
调用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
List<Employee> list = new List<Employee>();
list.Add(new Employee() { Name = "张三", Age = 21, Salary = 1800f, Job = "UI" });
list.Add(new Employee() { Name = "李四", Age = 25, Salary = 2000f, Job = "DBA" });
list.Add(new Employee() { Name = "王五", Age = 24, Salary = 2000f, Job = "UI" });
list.Add(new Employee() { Name = "李九", Age = 31, Salary = 2900f, Job = "DBA" });
list.Add(new Employee() { Name = "张一", Age = 21, Salary = 2100f, Job = "UI" });
list.Add(new Employee() { Name = "王三", Age = 32, Salary = 2100f, Job = "DBA" });
//按Age排序
list.OrderBy(DynamicLambda<Employee,int>("Age"));
//按Salary排序
// list.OrderBy(DynamicLambda<Employee,float>("Salary"));
list.ForEach(e => Console.WriteLine(e.Name + "\t" + e.Age + "\t" + e.Salary));
list.Add(new Employee() { Name = "张三", Age = 21, Salary = 1800f, Job = "UI" });
list.Add(new Employee() { Name = "李四", Age = 25, Salary = 2000f, Job = "DBA" });
list.Add(new Employee() { Name = "王五", Age = 24, Salary = 2000f, Job = "UI" });
list.Add(new Employee() { Name = "李九", Age = 31, Salary = 2900f, Job = "DBA" });
list.Add(new Employee() { Name = "张一", Age = 21, Salary = 2100f, Job = "UI" });
list.Add(new Employee() { Name = "王三", Age = 32, Salary = 2100f, Job = "DBA" });
//按Age排序
list.OrderBy(DynamicLambda<Employee,int>("Age"));
//按Salary排序
// list.OrderBy(DynamicLambda<Employee,float>("Salary"));
list.ForEach(e => Console.WriteLine(e.Name + "\t" + e.Age + "\t" + e.Salary));