Created
August 20, 2019 15:51
-
-
Save karoltheguy/924beeb59d49d22b4d48883457db9ec8 to your computer and use it in GitHub Desktop.
C# Sort by number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<string> list = new List<string>() { | |
"Liverpool - 1", | |
"Liverpool - 11", | |
"Liverpool - 12", | |
"Liverpool - 2", | |
"West Kirby - 1", | |
"West Kirby - 12", | |
"West Kirby - 8" }; | |
var sortedList = list.CustomSort().ToArray(); | |
public static class MyExtensions | |
{ | |
public static IEnumerable<string> CustomSort(this IEnumerable<string> list) | |
{ | |
int maxLen = list.Select(s => s.Length).Max(); | |
return list.Select(s => new | |
{ | |
OrgStr = s, | |
SortStr = Regex.Replace(s, @"(\d+)|(\D+)", m => m.Value.PadLeft(maxLen, char.IsDigit(m.Value[0]) ? ' ' : '\xffff')) | |
}) | |
.OrderBy(x => x.SortStr) | |
.Select(x => x.OrgStr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment