string strArr="5,3,8,1,9,2,0,6,4,7";
I would like to rearrange the order of the numbers so t开发者_Python百科he result will look like the following:
string result ="0,1,2,3,4,5,6,7,8,9";
Any idea?
Split, sort and join:
string[] nums = strArr.Split(',');
Array.Sort(nums);
string result = String.Join(",", nums);
Or:
string result =
String.Join(",",
strArr.Split(',')
.OrderBy(s => s)
.ToArray()
);
If you have a string with larger numbers that need to be sorted numerically, you can't sort them as strings, as for example "2" > "1000". You would convert each substring to a number, sort, and then convert them back:
string result =
String.Join(",",
strArr
.Split(',')
.Select(s => Int32.Parse(s))
.OrderBy(n => n)
.Select(n => n.ToString())
.ToArray()
);
Or, as mastoj suggested, parse the strings in the sorting:
string result =
String.Join(",",
strArr
.Split(',')
.OrderBy(s => Int32.Parse(s))
.ToArray()
);
Shorter version of one of the versions in Guffa's answer:
var res = String.Join(",", str.Split(',').OrderBy(y => int.Parse(y)).ToArray());
By splitting and joining:
string strArr = "5,3,8,1,9,2,0,6,4,7";
string[] sArr = strArr.Split(',');
Array.Sort(sArr);
string result = string.Join(",", sArr);
You can create a string
array with the string.split(char[])
method.
With this array you can call the Array.Sort(T)
method, that will sort the items into ascending numerical order (for your example).
With this sorted array you can call the String.Join(string, object[])
to pull it together into a string again.
string arr = "5,3,8,1,9,2,0,6,4,7";
string result = arr.Split(',').OrderBy(str => Int32.Parse(str)).Aggregate((current, next) => current + "," + next);
精彩评论