C# linq查询之动态OrderBy用法实例
程序员文章站
2023-12-04 17:58:10
本文实例讲述了c# linq查询之动态orderby用法。分享给大家供大家参考。具体分析如下:
grouplist是原始数据集合,list
sorto...
本文实例讲述了c# linq查询之动态orderby用法。分享给大家供大家参考。具体分析如下:
grouplist是原始数据集合,list<t>
sortorder是排序类型,desc 或者asc
sortname是排序属性名称
1.使用反射。
private static object getpropertyvalue(object obj, string property) { system.reflection.propertyinfo propertyinfo = obj.gettype().getproperty(property); return propertyinfo.getvalue(obj, null); } var resultlist = sortorder == "desc" ? grouplist.orderbydescending(p => getpropertyvalue(p, sortname)) : grouplist.orderby(p => getpropertyvalue(p, sortname)); //linq方式: // var resultlist1 = from p in grouplist orderby getpropertyvalue(p, m.sortname) select p; if (sortorder == "desc") resultlist1 = from p in grouplist orderby getpropertyvalue(p, sortname) descending select p;
2.调用asqueryable()
将泛型 system.collections.generic.ienumerable<t> 转换为泛型 system.linq.iqueryable<t>。
var groupquerylist = grouplist.asqueryable();//here var tmplist = groupquerylist.orderby(sortname, sortorder);
需要如下扩展方法:
public static iorderedqueryable<t> orderbydescending<t>(this iqueryable<t> source, string property) { return applyorder<t>(source, property, "orderbydescending"); } public static iorderedqueryable<t> thenby<t>(this iorderedqueryable<t> source, string property) { return applyorder<t>(source, property, "thenby"); } public static iorderedqueryable<t> thenbydescending<t>(this iorderedqueryable<t> source, string property) { return applyorder<t>(source, property, "thenbydescending"); } static iorderedqueryable<t> applyorder<t>(iqueryable<t> source, string property, string methodname) { string[] props = property.split('.'); type type = typeof(t); parameterexpression arg = expression.parameter(type, "x"); expression expr = arg; foreach(string prop in props) { // use reflection (not componentmodel) to mirror linq propertyinfo pi = type.getproperty(prop); expr = expression.property(expr, pi); type = pi.propertytype; } type delegatetype = typeof(func<,>).makegenerictype(typeof(t), type); lambdaexpression lambda = expression.lambda(delegatetype, expr, arg); object result = typeof(queryable).getmethods().single( method => method.name == methodname && method.isgenericmethoddefinition && method.getgenericarguments().length == 2 && method.getparameters().length == 2) .makegenericmethod(typeof(t), type) .invoke(null, new object[] {source, lambda}); return (iorderedqueryable<t>)result; }
希望本文所述对大家的c#程序设计有所帮助。