Sort string array by element length

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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?

回答1:

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.



回答2:

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


回答3:

You can also do this using Linq as below:

var sortedElements = from arrElement in arr.Distinct()                      orderby arrElement.Length                      select arrElement;  foreach (string element in sortedElements) {      ... } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!