I am using Linq and Lambda Operations in my projects and I needed to sort a List according to two properties of a class. Therefore, I used OrderBy().ThenBy() methods as below:
class ValueWithIndex{ public long Value; public int Index; } ... List<ValueWithIndex> valuesWithIndex = new List<ValueWithIndex>(); for (int i = 0; i < A.Length; i++){ ValueWithIndex vi = new ValueWithIndex(); vi.Value = A[i]; vi.Index = i; valuesWithIndex.Add(vi); } var orderedValues = valuesWithIndex.OrderBy(v => v.Value).ThenBy(v => v.Index); ...
In This answer, it is explained that, OrderBy() uses Quicksort, so even if it has O(N*logN) average time complexity, for the worst case, time complexity is around O(N2). If also ThenBy() method has a worst time complexity of O(N2), it would be pointless to use these methods.
Is ThenBy() method use Quicksort, too? If yes, does it mean that for the same "v.Value"s, "v.Index"es are sorted with O(N2) worst time complexity?
The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.
Sorts the elements of a sequence in ascending order according to a key. OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) Sorts the elements of a sequence in ascending order by using a specified comparer.
The ThenBy and ThenByDescending extension methods are used for sorting on multiple fields. The OrderBy() method sorts the collection in ascending order based on specified field. Use ThenBy() method after OrderBy to sort the collection on another field in ascending order.
For LINQ to Objects, it's a stable quicksort that is used.
The LINQ OrderBy(...).ThenBy(...)...ThenBy(...)
method chain form a single sort operation by multiple sort keys (using multi key comparer).
Thus, regardless of how many ThenBy(Descending)
methods do you include in the chain, the time complexity of the sort operation stays the typical for QuickSort O(N*logN) average / O(N2) worst case. Of course more keys you add, comparing two objects will take more time, but the complexity of the sort operation would not change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With