natural sort
Hi guys, I need to do some kind of sort on a collection of strings... the actual strings are something like
Generation1
, Generation2
, ... Generation10
so they should be sorted in a way that makes sense, right? I am on asp.net dotnet 6. If there is a way for me to do this without relying on the underlying os or a lot of code, that would be ideal. Thank you.12 Replies
hi, all the strings are "Generation" + number?
yes they are
I made a dotnet fiddle https://dotnetfiddle.net/MjH2Jo
naturalsort | C# Online Compiler | .NET Fiddle
naturalsort | Test your C# code online with .NET Fiddle code editor.
then just work with the numbers, split the word and the number, sort the result and when you need them just slap GenerationX again, implicitly you know they are all Generation + int
easier to work with numbers than strings
were you thinking something like this?
https://dotnetfiddle.net/MjH2Jo
naturalsort | C# Online Compiler | .NET Fiddle
naturalsort | Test your C# code online with .NET Fiddle code editor.
or is there a better way?
what about duplicates? you don't care about them?
well my input is a list of strings and sadly this is just for like a foreach of IEnumerable<string> to show a list of strings and the user picks a radio button.
I was hoping I could avoid writing any code for this :/
If the name is constant and just the number changes, no need for regex IMHO, just substring
I was hoping something like
strings.OrderBy(x => x, naturalsort)
yes like that
perfect, thank you guys. I knew it had to be something simple like that
one problem is how I will deal with a case if I get an unexpected input. right now this will cause the whole application to throw. I will check into it later but wanted to mention that here in case someone else reads this and decides to implement this.Or just use this: https://github.com/tompazourek/NaturalSort.Extension
GitHub
GitHub - tompazourek/NaturalSort.Extension: 🔀 Extension method for ...
🔀 Extension method for StringComparison that adds support for natural sorting (e.g. "abc1", "abc2", "abc10" instead of "abc1"...
That's what I use