I'm using Array.Sort() to sort an array of doubles into ascending order. And then in some cases I do a Reverse() to change the order. But ideally I'd like to preserve my original array. Does C# have a simple, native sort for arrays that outputs to a new array rather than sorting the existing array in-place?
1 Answer
You can use LINQ to do that:
var result = source.OrderBy(x => x).ToArray();
or for descending order:
var result = source.OrderByDescending(x => x).ToArray();
or you can create new array first and than sort it:
var newArray = (double[])source.Clone();
newArray.Sort();
I would expect the latter to be faster, but you should probably measure it to be sure.
1 Comment
Kryptos
It is faster especially with big arrays to use
Array.Sort(). Two reasons: OrderBy() first need to extract all keys (do the projection by executing the lamba on all values) so it iterates once over the whole array before doing the sorting. Then it uses quicksort internally whereas Array.Sort() use introsort (a mix between quicksort and heapsort) which gives better average performance. By the way it is faster to copy the array using Array.Copy instead of creating a clone.
OrderByLinq Method