Sort an int array with orderby

后端 未结 3 1425
-上瘾入骨i
-上瘾入骨i 2020-12-16 10:49

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

3条回答
  •  北海茫月
    2020-12-16 11:22

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

提交回复
热议问题