C # List. sort details (Multiple Weights, ascending and descending ),

Source: Internet
Author: User

C # List. sort details (Multiple Weights, ascending and descending ),

Many people may like the orderBy sorting of Linq. Unfortunately, in U3D, linq reports an error on Ios, so you must use list sorting.

Actually, it's not difficult to understand

 

 

 

Comparison of ascending and descending orders

Sort has three results: 1.-1 and 0 are big, small, and equal.

By default, the List is sorted in ascending order.

If you want to sort data in descending order, you can simply add a negative number to the front.

List<int> tmp = new List<int>(){5,1,22,11,4};tmp.Sort((x, y) => -x.CompareTo(y));Console.WriteLine(tmp);//22,11,5,4,1

 

For non-numeric type comparison, use the. CompareTo (...), based on the IComparable interface. Basically, all C # value types implement this interface, including string.

The value type can also be compared by yourself. During sorting, the left and right variables must be left-Compared-Right (compared). Remember not to use them in turn.

Parameters officially recommended by MicrosoftThe naming method is x (left), y (right)

 

 

Multi-weight comparison

 

Assume that the value of item2 in tuple takes precedence over item1. In this case, only the comparison result X is provided.

List<Tuple<int, int>> tmp = new List<Tuple<int, int>>(){    new Tuple<int,int>(2,1),    new Tuple<int,int>(53,1),    new Tuple<int,int>(12,1),    new Tuple<int,int>(22,3),    new Tuple<int,int>(1,2),};tmp.Sort((x, y) => -(x.Item1.CompareTo(y.Item1) + x.Item2.CompareTo(y.Item2) * 2));Console.WriteLine(tmp);//22,3//1,2//53,1//12,1//2,1

If you control the ascending and descending order separately, remove the braces and separate them.

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.