I want to sort an list of string that sometimes contains numeric values
My list is like this:
- Bedroom 1
- Bedroom 2
- Bedroom 10
- Bathroom 1
- Bathroom 2
- Bathroom 10
- 1 Light
- 1 Paper
If I just use an orderby: roomList.OrderBy(x => x.Name) I get this list:
- 1 Light
- 1 Paper
- Bathroom 1
- Bathroom 10
- Bathroom 2
- Bedroom 1
- Bedroom 10
- Bedroom 2
Is it possible to get the list like this instead ?
- 1 Light
- 1 Paper
- Bathroom 1
- Bathroom 2
- Bathroom 10
- Bedroom 1
- Bedroom 2
- Bedroom 10
All list elements don't contain a number, and the list is about 1500 rows long
I have tryed to use this code, and it works fine on elements containing number, but not on just string elements:
public class SemiNumericComparer : IComparer<string>
{
public int Compare(string s1, string s2)
{
if (IsNumeric(s1) && IsNumeric(s2))
{
if (Convert.ToInt32(s1) > Convert.ToInt32(s2)) return 1;
if (Convert.ToInt32(s1) < Convert.ToInt32(s2)) return -1;
if (Convert.ToInt32(s1) == Convert.ToInt32(s2)) return 0;
}
if (IsNumeric(s1) && !IsNumeric(s2))
return -1;
if (!IsNumeric(s1) && IsNumeric(s2))
return 1;
return string.Compare(s1, s2, true);
}
public static bool IsNumeric(object value)
{
try
{
int i = Convert.ToInt32(value.ToString());
return true;
}
catch (FormatException)
{
return false;
}
}
}