A wonderful use of sorting by using LINQ orderby

Source: Internet
Author: User

For sorting, sorting is found to be used in many places in the project. It is very tiring to write forward, backward, and backward orders. However, it is good to write a comprehensive method for sorting.

1. Obtain the data of XX.

Ienumerable <XXXX >= .....................;

2. Get the orderby parameter to be sorted.

Orderby parameter format:

Orderby = "createtime ASC, title DESC ";

--------------------------------------------------------------------------

Orderusingsortexpression (res. asqueryable (), orderby). asenumerable ();

3. sorting data

Public static iorderedqueryable <tentity> orderusingsortexpression <tentity> (this iqueryable <tentity> source, string sortexpression) Where tentity: Class
{
String [] orderfields = sortexpression. Split (',');
Iorderedqueryable <tentity> result = NULL;
For (INT currentfieldindex = 0; currentfieldindex <orderfields. length; currentfieldindex ++)
{
String [] expressionpart = orderfields [currentfieldindex]. Trim (). Split ('');
String sortfield = expressionpart [0];
Boolean sortdescending = (expressionpart. Length = 2) & (expressionpart [1]. Equals ("DESC", stringcomparison. ordinalignorecase ));
If (sortdescending)
{
Result = currentfieldindex = 0? Source. orderbydescending (sortfield): result. thenbydescending (sortfield );
}
Else
{
Result = currentfieldindex = 0? Source. orderby (sortfield): result. thenby (sortfield );
}
}
Return result;
}

4. In this way, no matter how many backend methods are sorted, only one orderby parameter is defined, which is fine according to certain specifications.

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.