Make the OrderBy function of Linq support dynamic fields, linqorderby

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.