Make the OrderBy function of Linq support dynamic fields, linqorderby
It is easy to use the OrderBy clause of linq if you know which field it is:
IQueryable<User> userQuery = ...; userQuery.OrderBy(u => u.Code)
But if we want to write a general method, we don't know which field to sort in advance?
Searching on the Internet, many domestic blogs are plagiarized with each other, but the Code cannot run.
It is also a good service for foreigners:
Http://www.4byte.cn/question/33782/dynamic-orderby-using-linq-dynamic.html
I modified it. You can use it. The main idea is to extend Queryable. But I cannot understand a lot of things in it.
public static class QueryableExtension { public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, string propertyName) { return _OrderBy<T>(query, propertyName, false); } public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> query, string propertyName) { return _OrderBy<T>(query, propertyName, true); } static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName,bool isDesc) { string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal"; var memberProp = typeof(T).GetProperty(propertyName); var method = typeof(QueryableExtension).GetMethod(methodname) .MakeGenericMethod(typeof(T), memberProp.PropertyType); return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp }); } public static IOrderedQueryable<T> OrderByInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty) {//public return query.OrderBy(_GetLamba<T, TProp>(memberProperty)); } public static IOrderedQueryable<T> OrderByDescendingInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty) {//public return query.OrderByDescending(_GetLamba<T, TProp>(memberProperty)); } static Expression<Func<T, TProp>> _GetLamba<T, TProp>(PropertyInfo memberProperty) { if (memberProperty.PropertyType != typeof(TProp)) throw new Exception(); var thisArg = Expression.Parameter(typeof(T)); var lamba = Expression.Lambda<Func<T, TProp>>(Expression.Property(thisArg, memberProperty), thisArg); return lamba; } }
Call:
IQueryable <User> userQuery =...; // Positive Sequence userQuery = userQuery. OrderBy ("Code"); // descending order userQuery = userQuery. OrderByDescending ("Code ");
Copyright Disclaimer: This article is the original author's article. If you like it, you can take it away.