0

I have some custom filenames I need to sort based on information in the filename itself.

I know there has to be an easier way than I have come up with (a for loop which goes through and manually splits the strings to identify the various filename info) using SortDescriptions but I can't figure them out.

The filename format is:

OurApp_versionNum_DEBUG_build_number.exe

e.g.

Notepad_1.0_DEBUG_build_1.exe

I want to sort the items with the highest build number at the top of the list box so e.g.

Notepad_1.0_DEBUG_build_10.exe

Notepad_1.0_DEBUG_build_7.exe

Notepad_1.0_DEBUG_build_1.exe

I know there must be a simpler way than what I've come up with. Any help is appreciated.

I am using .NET 4.0.

Thank you

m

Maximojo
  • 315
  • 5
  • 17

2 Answers2

0

I think you are looking for a customized natural sorting algorithm. See this discussion for an example implementation (the native C# one, by the author J.D.).

Definition from wikipedia:

Natural sort order is an ordering of strings in alphabetical order, except that multi-digit numbers are ordered as a single character

Unmodified, it will output your list as:

  • Notepad_1.0_DEBUG_build_1.exe
  • Notepad_1.0_DEBUG_build_7.exe
  • Notepad_1.0_DEBUG_build_10.exe

If all your entries have the same prefix, you can use just use the reverse comparison function:

public static int CompareNaturalReverse(string strA, string strB) {
    return -CompareNatural(strA, strB);
}

Otherwise, if you want to maintain the alphabetical order and onlye reverse the numerical order (because of different prefixes), you have to change the sorting implementation.

Community
  • 1
  • 1
ventiseis
  • 3,029
  • 11
  • 32
  • 49
-1

Sort the items before adding them to the listbox. A simple regex call could extract the number such as: (\\d+).exe if you know that's exactly how the file names will be.

Dispersia
  • 1,436
  • 9
  • 23