Sort an int array with orderby

后端 未结 3 1426
-上瘾入骨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:12

    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.

提交回复
热议问题