Sorting Strings when the Embedded Number has a Variable Number of Digits

Here is a short post on something that can catch people out at times when sorting strings.

If you have a list of strings that contain numbers like -

  • {"item2", "item4", "item1", "item3", "item11", "item12"}, and you perform a simple order by on them, you will get -
  • {"item1", "item11", "item12", "item2", "item3", "item4"}

Not what you want.

To resolve this, you need to isolate the number, convert it to an integer, and then sort on that. In this example, a simple Substring from the start of the number is enough. If the number was somewhere in the middle of the string, you would need to do a bit more work to isolate it before sorting on it.

 1string[] itemsToSort = { "item11", "item12", "item5", "item4", "item3", "item9", "item14", "item15", "item6", "item10", "item1", "item2", "item13", "item7", "item8" };
 2
 3// sort only by the string
 4var incorrectlySortedItems = itemsToSort.OrderBy(name => name);
 5
 6Console.WriteLine("Incorrectly sorted names:");
 7foreach (var name in incorrectlySortedItems)
 8{
 9    Console.WriteLine(name);
10}
11// output is item1, item10, item11...
12
13// correctly sort this list, isolating the number and converting to an int
14var correctlySortedItems = itemsToSort.OrderBy(name => int.Parse(name.Substring(4)));
15
16
17Console.WriteLine("Correctly sorted names:");
18foreach (var name in correctlySortedItems)
19{
20    Console.WriteLine(name);
21}
22// output is item1, item2, item3...

That’s it. Once you isolate the number and convert it to an integer, the problem becomes easy.

comments powered by Disqus

Related