C # Extended LINQ's Order by function supports specifying column names by string and supporting multiple columns

Source: Internet
Author: User

This paper draws on 68523451.

Converting a string to an order by LINQ can greatly reduce duplication of effort, but how do you convert multiple fields to the () and ThenBy () expressions? You can refer to the following code:

 Public StaticIorderedqueryable<t> orderby<t> ( ThisIqueryable<t> Q,stringcondition) {            string[] conditions = condition. Split (','); if(Conditions. length==0)            {                return(iorderedqueryable<t>) Q; } iorderedqueryable<T> res =NULL;  for(inti =0; I < conditions. Length; i++)            {                string[] strings = Conditions[i]. Split (" "); varFieldName = strings[0]; varDirection = strings[1]; varparam = Expression.parameter (typeof(T),"P"); varProp =expression.property (param, fieldName); varExp =expression.lambda (prop, param); stringmethod; if(i==0) {method= direction. ToLower () = ="ASC"?" by":"orderbydescending"; }                Else{method= direction. ToLower () = ="ASC"?"ThenBy":"thenbydescending"; } type[] Types={q.elementtype, exp.                Body.type}; varMCE = i==0? Expression.call (typeof(queryable), method, types, Q.expression, exp): Expression.call (typeof(queryable), method, types, res.                Expression, exp); if(Conditions. Length = =1)                {                    return(iorderedqueryable<t>) q.provider.createquery<t>(MCE); } Res= i = =0? (iorderedqueryable<t>) q.provider.createquery<t> (MCE): (iorderedqueryable<t>) Res. Provider.createquery<t>(MCE); }            returnRes; }

The IQueryable object calls the order by method, passing in the "Id desc,age desc" format string to enable multi-column sorting.

C # Extended LINQ's Order by function supports specifying column names by string and supporting multiple columns

Related Article

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.