-2

I am loading a listBox full of strings from a string array with a foreach statement. The strings say "Level 1" through "Level 20" and eventually further. It orders them as Level 1, Level 11, Level 12, Level 13, etc, skipping level 2, 3, 4 etc.

How can I order this correctly?

I am about to remove "Level " so it is just the numbers in the array then add them to the listBox with "Level " added. But performance is an issue with this WPF page and this may not be the best performance way.

Thanks.

user2602079
  • 1,283
  • 5
  • 20
  • 39
  • See: [Natural Sort Order in C#](http://stackoverflow.com/q/248603)/412770 – Ani Dec 09 '13 at 05:36
  • You should have some object with `Level` property, use some `SortDescription` based on that `Level` instead. That way we can order easily than based on the string presentation of the item. – King King Dec 09 '13 at 05:37

1 Answers1

1

Assuming the strings really do comprise a number prefixed with "Level " and that you already have an array of the strings then you could use this:

    var orderedEntries = from entry in entries orderby entry.Length, entry select entry;
    foreach (var entry in orderedEntries)
    {
        // TODO - add to WPF control
    }

However, from a performance perspective you'd be better off sorting an array of the numbers first and then prefixing each entry with "Level ".

StevieB
  • 982
  • 7
  • 15
  • Thanks. That way seems like it will work well but if my original idea is not any worse for performance, I will go with that as I've already done it. Good to know. – user2602079 Dec 09 '13 at 06:04