user1635406
user1635406

Reputation: 277

Sort an int array with orderby

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[]'"

Upvotes: 26

Views: 79265

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062780

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.

Upvotes: 28

weston
weston

Reputation: 54781

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.

Upvotes: 3

Jon
Jon

Reputation: 437376

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();

Upvotes: 58

Related Questions