我想动态的传给Linq一个对象的属性名,然后根据属性名进行排序操作,下面代码是在Linq中通过反射根据一个属性(FirstName)查找Person对象,但在运行时会报错.
请教linq lamda表达式中能这样使用吗?
schoolContext = new SchoolEntities();
IQueryable<Person> person = schoolContext.Person.Where<Person>(p => p.GetType().GetProperty("FirstName").GetValue(p, null).ToString() == "Kim");
foreach(Person p in person)
{
MessageBox.Show(p.LastName);
}
Dictionary<String, Func<User, IComparable>> list; userList = User.GetUserList(); list = new Dictionary<String, Func<User, IComparable>>(); list.Add("UserName", currentUser => currentUser.UserName); list.Add("UserID", currentUser => currentUser.UserID); //用反射动态添加自定义属性。 public static PropertyInfo[] GetInfo<K>(K item) where K : class { PropertyInfo[] propertyList; Type typeInfo; typeInfo = item.GetType(); propertyList = typeInfo.GetProperties(); return propertyList; } public static IComparable OrderByProperty<T>(String propertyName, T item) where T : class { PropertyInfo[] propertyList; propertyList = GetInfo(item); return (IComparable)propertyList.First(currentProperty => currentProperty.Name == propertyName).GetValue(item, null); } //排序例子。 var test = userList.OrderBy(currentUser => DynamicPropertySort.OrderByProperty("UserID", currentUser)).ToList();
userList = User.GetUserList();
这句是什么意思没搞懂?
@bluefirework: 一个泛型集合,你可以换成你的。
@荒野的呼唤:
上边定义的Dictionary<String, Func<User, IComparable>> list程序里边咋个没用到呢?
反射,这个还真没用到,也相学习了。!