Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an int array with orderby

Tags:

c#

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 would like to sort it in ascending order like this:

 int[] sortedCopy = from element in copyArray 
                    orderby element ascending select element;

But I get a error, "selected" gets highligted and the error is: "cannot implicitly convert type 'system.linq.iorderedenumerable' to 'int[]'"

like image 245
user1635406 Avatar asked Sep 10 '25 15:09

user1635406


2 Answers

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();
like image 120
Jon Avatar answered Sep 12 '25 05:09

Jon


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.

like image 39
Marc Gravell Avatar answered Sep 12 '25 05:09

Marc Gravell