C# linq查询之动态OrderBy用法实例
本文实例讲述了C#linq查询之动态OrderBy用法。分享给大家供大家参考。具体分析如下:
groupList是原始数据集合,List<T>
sortOrder是排序类型,desc或者asc
sortName是排序属性名称
1.使用反射。
privatestaticobjectGetPropertyValue(objectobj,stringproperty) { System.Reflection.PropertyInfopropertyInfo=obj.GetType().GetProperty(property); returnpropertyInfo.GetValue(obj,null); } varresultList=sortOrder=="desc"?groupList.OrderByDescending(p=>GetPropertyValue(p,sortName)):groupList.OrderBy(p=>GetPropertyValue(p,sortName)); //linq方式: // varresultList1=frompingroupListorderbyGetPropertyValue(p,m.SortName)selectp; if(sortOrder=="desc") resultList1=frompingroupListorderbyGetPropertyValue(p,sortName)descendingselectp;
2.调用AsQueryable()
将泛型System.Collections.Generic.IEnumerable<T>转换为泛型System.Linq.IQueryable<T>。
vargroupQueryList=groupList.AsQueryable();//here vartmpList=groupQueryList.OrderBy(sortName,sortOrder);
需要如下扩展方法:
publicstaticIOrderedQueryable<T>OrderByDescending<T>(thisIQueryable<T>source,stringproperty) { returnApplyOrder<T>(source,property,"OrderByDescending"); } publicstaticIOrderedQueryable<T>ThenBy<T>(thisIOrderedQueryable<T>source,stringproperty) { returnApplyOrder<T>(source,property,"ThenBy"); } publicstaticIOrderedQueryable<T>ThenByDescending<T>(thisIOrderedQueryable<T>source,stringproperty) { returnApplyOrder<T>(source,property,"ThenByDescending"); } staticIOrderedQueryable<T>ApplyOrder<T>(IQueryable<T>source,stringproperty,stringmethodName){ string[]props=property.Split('.'); Typetype=typeof(T); ParameterExpressionarg=Expression.Parameter(type,"x"); Expressionexpr=arg; foreach(stringpropinprops){ //usereflection(notComponentModel)tomirrorLINQ PropertyInfopi=type.GetProperty(prop); expr=Expression.Property(expr,pi); type=pi.PropertyType; } TypedelegateType=typeof(Func<,>).MakeGenericType(typeof(T),type); LambdaExpressionlambda=Expression.Lambda(delegateType,expr,arg); objectresult=typeof(Queryable).GetMethods().Single( method=>method.Name==methodName &&method.IsGenericMethodDefinition &&method.GetGenericArguments().Length==2 &&method.GetParameters().Length==2) .MakeGenericMethod(typeof(T),type) .Invoke(null,newobject[]{source,lambda}); return(IOrderedQueryable<T>)result; }
希望本文所述对大家的C#程序设计有所帮助。