Sort string array by element length

前端 未结 3 504
既然无缘
既然无缘 2020-12-16 03:07

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\"};
a         


        
3条回答
  •  温柔的废话
    2020-12-16 03:30

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

提交回复
热议问题