I would like to sort my int array in ascending order.
first I make a copy of my array:
int[] copyArray = myArray.ToArray();
Then I
Note: if you don't need a copy (i.e. it is acceptable to change myArray
), then a much simpler and more efficient approach is just:
Array.Sort(myArray);
This does an in-place sort of the array, exploiting the fact that it is an array to be as efficient as possible.
For more complex scenarios (for example, a member-wise sort of an object-array), you can do things like:
Array.Sort(entityArray, (x,y) => string.Compare(x.Name, y.Name));
this is the moral-equivalent of:
var sortedCopy = entityArray.OrderBy(x => x.Name).ToArray();
but again: doing the sort in-place.
We don't know what you are doing next, but maybe you don't need an array. If it's going into another linq statement, or foreach, then just keep it as it is, most simply by using var
.
var sortedCopy = myArray.OrderBy(i => i);
foreach(var item in sortedCopy)
{
//print out for example
}
This allows linq to be as lazy as possible. If you always cast ToArray
or ToList
then it has no choice than to evaluate then and there, and allocate memory for the result.
You need to call ToArray()
at the end to actually convert the ordered sequence into an array. LINQ uses lazy evaluation, which means that until you call ToArray()
, ToList()
or some other similar method the intermediate processing (in this case sorting) will not be performed.
Doing this will already make a copy of the elements, so you don't actually need to create your own copy first.
Example:
int[] sortedCopy = (from element in myArray orderby element ascending select element)
.ToArray();
It would perhaps be preferable to write this in expression syntax:
int[] sortedCopy = myArray.OrderBy(i => i).ToArray();