1
    2.1-hello
    2.2-world
    2.3-people
    2.10-everywhere

results in this when items are added to a SortedDictionary<String,String>

    2.1-hello
    2.10-everywhere
    2.2-world
    2.3-people

What is the best way to get the sort with the behavior decimal/numeric order before the "-" character, with conventional ASCII order/collation after that? Original code was splitting on the "-" and converting the initial parts, which is really not efficient. All ideas appreciated.

Thanks.

Snowy
  • 5,942
  • 19
  • 65
  • 119
  • `SortedDictionary` does not compile. Please add more detail to you specific requirements and provide code you have already tried. – Barns May 31 '21 at 18:56
  • @Barns SortedDictionary is what I meant. Thanks for identifying that. – Snowy Jun 01 '21 at 01:31

1 Answers1

3

This is a duplicate of Natural Sort Order in C#

But if you want a simple solution that works with your specific use-case you could have a look at the following. I don't split on the delimiter - but use IndexOf + Remove which is more efficient. For the natural sorting i'm using the Version class:

var list = new List<string>{"2.1-hello","2.2-world","2.3-people","2.10-everywhere", "foo"};
list = list
    .Select(s => (String:s,Version:GetVersion(s), LastPart:GetLastPart(s)))
    .OrderBy(x => x.Version)
    .ThenBy(x => x.LastPart)
    .Select(x => x.String)
    .ToList();

private static Version GetVersion(string s, string delimiter = "-")
{
    int index = s.IndexOf(delimiter);
    if(index == -1) return null;
    return Version.TryParse(s.Remove(index), out Version v) ? v : null;
}

private static string GetLastPart(string s, string delimiter = "-")
{
    int index = s.IndexOf(delimiter);
    if (index == -1) return s;
    return s.Substring(index + delimiter.Length);
}

.Net Fiddle

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939