Split, sort and merge:
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 large numbers that you need to sort numerically, you cannot sort them as strings, for example, "2"> "1000". You convert each substring to a number, sort, and then convert back:
string result =
String.Join(",",
strArr
.Split(',')
.Select(s => Int32.Parse(s))
.OrderBy(n => n)
.Select(n => n.ToString())
.ToArray()
);
Or, as suggested by masta, parse the lines in the sort:
string result =
String.Join(",",
strArr
.Split(',')
.OrderBy(s => Int32.Parse(s))
.ToArray()
);
source
share