I have an List of strings that I will pull from an enum and I need to sort in alphabetical order then by number and some strings won't have numbers, those strings should be at the end of the list.
List =
"Incl 11
Incl 12
Excl 4
Incl 3
Other
Incl 4
Incl 10
Incl 11
Excl 10
Incl 1
Incl 2
Withdrew Col
Excl 1
Excl 2
Excl 3
Follow Up
"
So far I have this but it's only sorted by number and not alphabetically first, any help would be appreciated.
var test = Enum.GetValues(typeof(Reason))
.Cast<Reason>()
.Select(sc => new SelectListItem { Value = ((int)sc).ToString(), Text = sc.GetDisplayName() })
.OrderBy(s => s.Text, new MyNumberComparer())
.ToList();
class MyNumberComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var xResultString = Regex.Match(x, @"\d+").Value;
var yResultString = Regex.Match(y, @"\d+").Value;
int xVal, yVal;
var xIsVal = int.TryParse(xResultString, out xVal);
var yIsVal = int.TryParse(yResultString, out yVal);
if (xIsVal && yIsVal)
return xVal.CompareTo(yVal);
if (!xIsVal && !yIsVal)
return x.CompareTo(y);
if (xIsVal)
return -1;
return 1;
}
}
Edit with what the final output should be:
List =
"Excl 1
Excl 2
Excl 3
Excl 4
Excl 10
Incl 1
Incl 2
Incl 3
Incl 4
Incl 10
Incl 11
Incl 12
Follow Up
Other
Withdrew Col
"