本文介绍了排序字符串数组按元素长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有串我怎么可以更新它的数组所以它的元素通过其长度排序。
Having an array of strings how can I update it so its elements are sorted by its length.
我试图
string[] arr = {"aa","ss","a","abc"};
arr = arr.OrderBy(aux => aux.Length);
所以,我会得到 A,AA,SS,ABC
,但它说
不能隐式转换类型'system.linq.iorderedenumerable
字符串[]
所以,我是做
foreach (string s in arr.OrderBy(str => str.Length))
{
//
}
有没有其他办法可以做到这一点?
Is there other way to do this?
推荐答案
由于改编
是一个数组,你可以使用便捷的<$c$c>Array.Sort方法:
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.
这篇关于排序字符串数组按元素长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!