After the analysis of the previous two articles, we have learned the difference between the two implementations of Array.sort<t> and LINQ: The former directly compares the size of two elements, while the latter selects the "sort basis" for each element before comparing. Therefore, while the latter requires relatively large "perimeter work", the performance of both is difficult to discern, as a whole, because it is possible to use only efficient underlying types (such as int) for each comparison. But now that we know why LINQ sorting is "efficient", can we use it on array sorting? Programs are written by people, and most of these questions have positive answers. So let's do it now.
API Design
On this issue, I have envisioned several API usage and design methods. For example, I initially wanted to use the "standard" extension method:
Person[] people = null;
people
.OrderBy(p => p.Age) // 指定主要排序规则
.OrderBy(p => p.ID, true /* decending */) // 指定次要排序规则
.Sort(); // 排序
In such an API, the first two order by methods are used to "collect sorting criteria," and the array is sorted in the last sort method. This API is not a big problem to use, but it has two drawbacks in implementation. First of all, for the array, there is already defined on its order by method, the new extension method and class library duplicate name, do you want me to change the names? I hate to move the brain. Secondly, if the first by method is defined as an extension method on an array, is the second by method also an extension method of the array?
Fact Now that we're going to "collect" the collation, it's bound to need to be saved with an object--called Ordercriteria. Then the first by method returns such a Ordercriteria object, and the second by is defined on the Ordercriteria class. So, do we need to implement the "whole set of" by-method for arrays and Ordercriteria classes? This is really a matter of trouble ah.
So, I thought of this interface again:
new ArraySorter<Person>(people)
.OrderBy(p => Age)
.OrderBy(p => p.ID, true)
.Sort();
In so doing, we simply define a arraysorter type and then provide a set of order by method. This is not just labor-saving, but the "unified" sorting portal has another benefit, because we can implement this logic:
var sorter = new ArraySorter<Person>(people);
if (shouldOrderByAge)
{
sorter.OrderBy(p => p.Age);
}
if (shouldOrderById)
{
sorter.OrderBy(p => p.ID);
}
sorter.Sort();