Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...