Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort String list with Numeric Values

Tags:

c#

sorting

linq

I have a list of string, which is most likely, but not guaranteed to contain a list of numerics, i.e.,

{"1", "6", "2", "21", "89"}

What is the way to sort the string list so that it will always appear in ascending order?

I can't parse the string to numeric first before doing the sorting simply because the string can contain non numeric characters. And I don't want to go through the list and check-cast each component to numerics and do the sorting. Is there already a library existing out there for this purpose?

In the case where we have mix numerics and non-numeric string item, numeric strings always take precedence over the non numeric ones.

like image 700
Graviton Avatar asked Feb 07 '10 14:02

Graviton


People also ask

How do I sort numbers in a string?

Convert each element in the String array obtained in the previous step into an integer and store in into the integer array. The sort() method of the Arrays class accepts an array, sorts the contents of it in ascending order. Sort the integer array using this method.


2 Answers

This has been asked before slightly differently, but the same answer still applies, as they have a C# implementation on the same site.

SO Question: Sort on a string that may contain a number

Answer provided by ScArcher2: The Alphanum Algorithm

like image 86
Nick Craver Avatar answered Oct 19 '22 05:10

Nick Craver


You want to sort elements, just like Windows XP Explorer does with files. See this article on how to do this.

like image 26
Steven Avatar answered Oct 19 '22 05:10

Steven