Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...