. NET collection sort and you can play it like that.

Source: Internet
Author: User

Background:
 Public classstockquantity { PublicStockquantity (stringStatus, DateTime datetime,intquantity) {Status=status; DateTime=DateTime; Quantity=quantity; }         Public stringStatus {Get;Set; }  Publicdatetime datetime {Get;Set; }  Public intQuantity {Get;Set; }}


The object, which has three fields, is now the business need to have a type of list<stockquantity> collection stockquantities, which needs to be sorted three times, sorted and prioritized as follows:
1. The status is empty in the back, not empty row in front, do not care about the status of content, only care about the status is empty.
2. DateTime sort in ascending order.
3. Quantity in ascending order.

Little white My approach:

I only know can be set with Oderby sort, to the above three rules, so the design ideas are as follows.

1. Stockquantities.orderby (U=>u.status)
Error
This sort rule will not only consider whether the status is empty, but also the content of the status.
If the status is ["B", "C", NULL, "D"], then the sort result is [null, "B", "C", "D"].
And the result we want is ["B", "C", "D", null] (just throw the null to the last, the other does not move)
What to do?

Don't know for a moment, don't care

2. Sort the DateTime in ascending order, which is simple
Stockquantities.orderby (U=>u.datetime)
Half Right!
Why half-right, look underneath

3. Under the premise of sorting 2, use the order by order, namely Stockquantities.orderby (U=>u.datetime). (u=>u.quantity)
Error!
The expression above is equivalent to the following two-bar expression:

Stockquantities = Stockquantities.orderby (u=>= Stockquantities.orderby (u=>u.quantity)

So the first piece of code is the scrap code, and the final sort is sorted by quantity.
Although I am small white, but I still understand this is wrong, so my practice is

Stockquantities = Stockquantities.orderby (U =u.datetime).            ToList (); foreach(varDateOrderinchstockquantities) {                varDatetimeorderby = stockquantities.where (U = u.datetime.date = = dateOrder.DateTime.Date). (U =u.count); foreach(varCountorderinchDatetimeorderby) {                    if(Countorder.output = =false) {Console.WriteLine ($"{Countorder.status}-{countorder.datetime}-{countorder.count}"); Countorder.output=true; }}} Console.readkey ();


In order to prevent duplicate output, I also added the output property to the Stockquantity object, using a double loop, first taking the data dateorder sorted by time, and then all the data on the same day and sorting the quantity. When the property is False, the contents of the object are output, and the output property is set to true so that no duplication is made, and the datetime is sorted before the quantity is sorted.
So easy!!
However, when happy to put such a code submitted, but colleagues mercilessly despised, said: "What bad code Ah!" "But there's a better code than that?" he said.

Poured a cup of tea to the colleague, ordered a cigarette, humbly consult.

Big guy Procedure:


My colleague told me two strokes, namely, conditional sorting, multilevel sorting.

What is conditional sorting and how is it used?

1. Stockquantities.orderby (U=>u.status==null)
This is the conditional ordering, but I see, give a person is the status of the empty row in front, not an empty row behind the illusion.
Actually, we see one in the order of order. The return value is an expression of type bool, which first rows the result to 0 (false), and the result is 1 (true) . This sort considers only the bool value returned, regardless of the parameter's value, so let's say it is a conditional sort.
Fully complies with the requirements of collation 1.

What is a multilevel sort, how to use it?


2. Use my above my code sort although can realize first row datetime, then row quantity, but the time complexity of the algorithm n*n, and to stockquantity added output field, obviously unscientific.
However, the continuous use of multiple despair will eventually only take effect on the last one, the next, so this time should use ThenBy!!
Using ThenBy, you can say that the above three collations are simplified as follows:
Stockquantities = Stockquantities.orderby (U = u.status==null). ThenBy (U = u.datetime). ThenBy (U = u.quantity). ToList ();
Can be perfectly implemented again before a sort of the premise of the two-level sequencing.

The complete code after optimization is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;namespaceorderby{classProgram {Static voidMain (string[] args) {            varStockquantities =NewList<stockquantity>()            {                NewStockquantity ("Normal Product",NewDateTime ( .,4, -), A ),                NewStockquantity ("Normal Product",NewDateTime ( .,4, -), the ),                NewStockquantity ("Defective",NewDateTime ( .,4, -),Ten ),                NewStockquantity ("Defective",NewDateTime ( .,4, -),8 ),                NewStockquantity (NULL,NewDateTime ( .,4, -),8 ),            }; stockquantities = Stockquantities.orderby (U = u.status==null). ThenBy (U = u.datetime). ThenBy (U =u.quantity). ToList ();            foreach(varStockquantityinchstockquantities) {Console.WriteLine ($"{stockquantity.status}-{stockquantity.datetime}-{stockquantity.quantity}");        } console.readkey (); }    }     Public classstockquantity { PublicStockquantity (stringStatus, DateTime datetime,intquantity) {Status=status; DateTime=DateTime; Quantity=quantity; }         Public stringStatus {Get;Set; }  Publicdatetime datetime {Get;Set; }  Public intQuantity {Get;Set; } }}

A simple sort of optimization, the time complexity of the program from N*n to N, so here the two sorting skills to share out, I hope the students will not be helpful.

. NET collection sort and you can play it like that.

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.