<分区>
我想对有时包含数值的字符串列表进行排序
我的列表是这样的:
- 卧室 1
- 卧室 2
- 卧室 10
- 浴室 1
- 浴室 2
- 浴室 10
- 1 盏灯
- 1 篇论文
如果我只使用 orderby: roomList.OrderBy(x => x.Name) 我得到这个列表:
- 1 盏灯
- 1 篇论文
- 浴室 1
- 浴室 10
- 浴室 2
- 卧室 1
- 卧室 10
- 卧室 2
是否可以像这样获取列表?
- 1 盏灯
- 1 篇论文
- 浴室 1
- 浴室 2
- 浴室 10
- 卧室 1
- 卧室 2
- 卧室 10
所有列表元素都不包含数字,列表长约 1500 行
我已经尝试使用这段代码,它在包含数字的元素上运行良好,但不适用于字符串元素:
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;
}
}
}