使用reflection排序列表
我有一个表,我想为每列做排序function。
排序有两个方向asc和desc。
1)如何使用reflection对列进行排序?
List GetSortedList(List persons, string direction, string column) { return persons.OrderBy(x => GetProperyByName(x, column)); //GetPropertyByName - ?? }
2)我也想做一些我称之为linq运算符链的东西:
List GetSortedList(List persons, string direction, string column) { var linqChain; if(direction=="up") { linqChain+=persons.OrderBy(x => GetProperyByName(x, column)) } else { linqChain+=persons.OrderByDescending(x => GetProperyByName(x, column)) } linqChain+=.Where(....); return linqChain.Execute(); }
1)如果要使用列的字符串名称进行排序,请使用Dynamic LINQ库。
if (direction == "ASC") return persons.OrderBy(column); else return persons.OrderByDescending(column);
2)您可以使用表达式对象将LINQ表达式连接在一起。
Expression linqChain = persons; if (direction == "up") { linqChain = linqChain.OrderBy(column); } else { linqChain = linqChain.OrderByDescending(column); } linqChain = linqChain.Where(...); return linqChain.Execute();
尝试这样的事情
public void SortListByPropertyName(List list, bool isAscending, string propertyName) where T : IComparable { var propInfo = typeof (T).GetProperty(propertyName); Comparison asc = (t1, t2) => ((IComparable) propInfo.GetValue(t1, null)).CompareTo(propInfo.GetValue(t2, null)); Comparison desc = (t1, t2) => ((IComparable) propInfo.GetValue(t2, null)).CompareTo(propInfo.GetValue(t1, null)); list.Sort(isAscending ? asc : desc); }
这样做的简单方法是使用Dynamic LINQ 。