動態linq

wl1121發表於2009-06-12

 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();
        }

 應用:

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));