【发布时间】:2019-08-20 10:11:21
【问题描述】:
我想对有时包含数值的字符串列表进行排序
我的清单是这样的:
- 卧室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;
}
}
}
【问题讨论】:
-
你想用“2 Light”和“10 Light”发生什么? “浴室蓝”呢?
-
不确定这是否适合您,但您可以编辑字符串以使用前导零。
Bathroom 001、Bathroom 002等。或者,在运行时将数字部分转换为该格式,然后排序。 -
两者都应该在“边缘情况”场景中有所不同。如果您有具体的问题,请在您的数据上尝试一个。但我很确定,如果它不是一个完全任意的规则,那么它要么是一个骗子,要么是一个内置函数。自从我们开始拥有计算机以来,人类一直在要求有序的清单。我希望开发人员在后天找到一个简单的解决方案。