Sort string array by element length

.net, arrays, c#, sorting, string

Solution

Since `arr` is an array, you can use the convenient `Array.Sort` method:

Array.Sort(arr, (x, y) => x.Length.CompareTo(y.Length));
foreach (string s in arr)
{
    ...
}

This is more efficient than `OrderBy` as it will sort the elements of the array in place rather than creating a new collection to enumerate.

Problem

Having an array of strings how can I update it so its elements are sorted by its length. I was trying ``` string[] arr = {"aa","ss","a","abc"}; arr = arr.OrderBy(aux => aux.Length); ``` So, I would get `a,aa,ss,abc`, but it says cannot implicitly convert type 'system.linq.iorderedenumerable to string[]' So, I was doing ``` foreach (string s in arr.OrderBy(str => str.Length)) { // } ``` Is there other way to do this?

Original source