Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort string array by element length

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?

like image 914
edgarmtze Avatar asked Nov 20 '13 04:11

edgarmtze


People also ask

How do you sort a string array by length?

To sort the array by its string length, we can use the Array. sort() method by passing compare function as an argument. If the compare function return value is a. length - b.

How do you sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.


2 Answers

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.

like image 129
p.s.w.g Avatar answered Sep 29 '22 22:09

p.s.w.g


OrderBy returns IEnumerable, not an array. Use ToArray method to get an array:

arr = arr.OrderBy(aux => aux.Length).ToArray();

However, it will not sort the source array. Instead of that, it will create a new one with items sorted and replace the reference. If you need in-place sort (e.g. when the array is also referenced elsewhere) use Array.Sort method:

Array.Sort(x, (x1, x2) => x1.Length.CompareTo(x2.Length));
like image 39
MarcinJuraszek Avatar answered Sep 29 '22 22:09

MarcinJuraszek