使用Linq动态属性排序
使用反射:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.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://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.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));