Set sorting in. Net can play like this, you know

Time:2020-1-12

Overview of C-SET types

Collection is an important part of. Net FCL (Framework Class Library). All collection classes inherit from IEnumerable. Collection classes can be divided into the following categories: Association / non association type collection, sequential / random access collection, sequential / unordered collection, generic / non generic collection, thread safety collection.

Bottom interface diagram of each collection class

Background:


public class StockQuantity
 {
 public StockQuantity(string status, DateTime dateTime, int quantity)
 {
  Status = status;
  DateTime = dateTime;
  Quantity = quantity;
 }
 public string Status { get; set; }
 public DateTime DateTime { get; set; }
 public int Quantity { get; set; }
}

The object mainly has three fields. Now, the business requirement is to get a set of stockquantities of type list < stockquantity > and sort the set three times. The sorting rules and priorities are as follows:

1. If status is empty, it will be listed at the back. If status is not empty, it will be listed at the front. It does not care about the content of status, but only whether status is empty.

2. Sort datetime in ascending order.

3. Quantity ascending sorting.

What Xiaobai did:

I only know that we can use oderby to sort the sets. For the above three rules, the design idea is as follows.

1.    StockQuantities.OrderBy(u=>u.Status)

Mistake,

The sorting rules not only consider whether status is empty, but also consider the content of status.

If status is[“b”,”c”,null,”d”] , the sorting result is[null,“b”,”c”,”d”]

And what we want is[“b”,”c”,”d” ,null](just leave the null one at the end, nothing else)

What should I do?

I don’t know for the time being

2. Sort datetime in ascending order, which is simple

StockQuantities.OrderBy(u=>u.DateTime)

Half right!

Why half right? Look down

3. On the premise of sorting 2, use orderby, that isStockQuantities.OrderBy(u=>u.DateTime).OrderBy(u=>u.Quantity)

Wrong!

The above expression is equivalent to the following two expressions:


StockQuantities = StockQuantities.OrderBy(u=>u.DateTime)
StockQuantities = StockQuantities.OrderBy(u=>u.Quantity)

So the first code is the waste code, and the final sorting is based on quantity.

Although I am Xiaobai, I still understand that this is wrong, so my approach is


stockQuantities = stockQuantities.OrderBy(u => u.DateTime).ToList();
  foreach (var dateOrder in stockQuantities)
  {
  var datetimeOrderBy = stockQuantities.Where(u => u.DateTime.Date == dateOrder.DateTime.Date) .OrderBy(u => u.Count);
  foreach (var countOrder in datetimeOrderBy)
  {
   if (countOrder.OutPut == false)
   {
   Console.WriteLine($"{countOrder.Status}-{countOrder.DateTime}-{countOrder.Count}");
   countOrder.OutPut = true;
   }
  }
  }
  Console.ReadKey();

Using a double-layer loop, first get the data dateorder sorted by time, and then go to all the data in the same day with the data and sort the quantity. In order to prevent repeated output, I added the output attribute to the stockquantity object at the same time. When the attribute is false, the content of the object will be output, and the output attribute will be set to true, so that there will be no repeated output, Moreover, it implements sorting datetime first, and then quantity.
So Easy!!

However, after happily submitting such code, he was despised by his colleagues and said, “what rotten code!” But there’s better code than that?

I poured a cup of tea and lit a cigarette for my colleagues. I asked them modestly.

How to do it:

My colleague told me two ways: conditional sorting and multi-level sorting.

What is conditional sorting and how to use it?

1.    StockQuantities.OrderBy(u=>u.Status==null)

This is conditional sorting, but at first, it gives people the illusion that the status is empty at the front and not empty at the back.

In fact, we can see an expression with return value of bool type in orderby. The sorting results are 0 (false) first, and then 1 (true). This sort only considers the returned bool value, not the specific value of the parameter, so let’s call it conditional sort.

It fully meets the requirements of collation 1.

What is multi-level sorting and how to use it?

2. Although I can use my code sorting above to arrange datetime first and then quantity, the time complexity of the algorithm is n * n, and the output field is added to stockquantity, which is obviously unscientific.

However, using multiple orderbys in a row will only take effect on the last orderby. There is no way out of the world, so you should use thenby!!
With theby, the above three sorting rules can be simplified as follows:

stockQuantities = stockQuantities.OrderBy(u => u.Status==null).ThenBy(u => u.DateTime).ThenBy(u => u.Quantity).ToList();

It can perfectly realize the second level sorting under the premise of the previous sorting.

The optimized code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
namespace OrderBy
{
 class Program
 {
 static void Main(string[] args)
 {
  var stockQuantities = new List<StockQuantity>()
  {
  New stockquantity ("normal product", new datetime (2017, 4, 16, 12),
  New stockquantity ("normal product", new datetime (2017, 4, 17, 15),
  New stockquantity ("defective products", new datetime (2017,4,16), 10),
  New stockquantity ("defective products", new datetime (2017,4,17), 8),
  new StockQuantity(null,new DateTime(2017,4,18),8 ),
  };

  stockQuantities = stockQuantities.OrderBy(u => u.Status==null).ThenBy(u => u.DateTime).ThenBy(u => u.Quantity).ToList();

  foreach (var stockQuantity in stockQuantities)
  {
  Console.WriteLine($"{stockQuantity.Status}-{stockQuantity.DateTime}-{stockQuantity.Quantity}");
  }
  Console.ReadKey();
 }
 }

 public class StockQuantity
 {
 public StockQuantity(string status, DateTime dateTime, int quantity)
 {
  Status = status;
  DateTime = dateTime;
  Quantity = quantity;
 }
 public string Status { get; set; }
 public DateTime DateTime { get; set; }
 public int Quantity { get; set; }
 }
}

A simple sorting optimization can reduce the time complexity of the program from n * n to N, so share these two sorting skills here, hoping to help students who will not.

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.