C
C#3y ago
nepalbhasa

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
Henkypenky
Henkypenky3y ago
hi, all the strings are "Generation" + number?
nepalbhasa
nepalbhasaOP3y ago
yes they are
nepalbhasa
nepalbhasaOP3y ago
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.
Henkypenky
Henkypenky3y ago
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
nepalbhasa
nepalbhasaOP3y ago
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.
nepalbhasa
nepalbhasaOP3y ago
or is there a better way?
Henkypenky
Henkypenky3y ago
what about duplicates? you don't care about them?
nepalbhasa
nepalbhasaOP3y ago
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 :/
Angius
Angius3y ago
If the name is constant and just the number changes, no need for regex IMHO, just substring
var sorted = unsorted.OrderBy(x => int.Parse(x[10..]));
var sorted = unsorted.OrderBy(x => int.Parse(x[10..]));
nepalbhasa
nepalbhasaOP3y ago
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.
reacher
reacher3y ago
GitHub
GitHub - tompazourek/NaturalSort.Extension: 🔀 Extension method for ...
🔀 Extension method for StringComparison that adds support for natural sorting (e.g. &quot;abc1&quot;, &quot;abc2&quot;, &quot;abc10&quot; instead of &quot;abc1&quot;...
reacher
reacher3y ago
That's what I use
Want results from more Discord servers?
Add your server