C#字符串自定义排序

排序要求:按数字、文字、字母、符号的优先顺序排序

未排序:
yyds
1
air
2
#30
10
第8号
13
azure

系统默认排序结果:

#30
1
10
13
2
air
azure
yyds
第8号

要求排序后:

1
2
10
13
第8号
air
azure
yyds
#30

private void StringSort()
{
	List<string> list = new List<string>()
	{
		"azure",
		"1",
		"air",
		"2",
		"#30",
		"10",
		"第8号",
		"13",
		"yyds"
	};

    var sorted = list.OrderBy(o => o, MyComparer .Instance);
}

class MyComparer : IComparer<string>
{
	public static readonly MyComparer Instance = new MyComparer();

	public static readonly string RegexNum = @"^[0-9]+";
	public static readonly string RegexHan = @"^[\u4e00-\u9fa5]+";
	public static readonly string RegexLetter = @"^[A-Za-z]+";
	public static readonly string RegexSymbol = @"^[^0-9A-Za-z\u4e00-\u9fa5]+";

	public int Compare(string x, string y)
	{
		if (double.TryParse(x, out double xd) && double.TryParse(y, out double yd))
		{
			//均由数字组成的比较
			return (int)(xd - yd);
		}
		else
		{
			bool xIsNum = Regex.IsMatch(x, RegexNum);
			bool yIsNum = Regex.IsMatch(y, RegexNum);

			bool xIsHan = Regex.IsMatch(x, RegexHan);
			bool yIsHan = Regex.IsMatch(y, RegexHan);

			bool xIsLetter = Regex.IsMatch(x, RegexLetter);
			bool yIsLetter = Regex.IsMatch(y, RegexLetter);

			bool xIsSymbol = Regex.IsMatch(x, RegexSymbol);
			bool yIsSymbol = Regex.IsMatch(y, RegexSymbol);


			if ((xIsNum && yIsNum) || (xIsHan && yIsHan) || (xIsLetter && yIsLetter) || (xIsSymbol && yIsSymbol))
			{
				//同样的字符开头,则正常比较
				return string.Compare(x, y);
			}
			else
			{
				//以数字、文字、字母、符号排序
				if (xIsNum)
				{
					return -1;
				}
				else if (yIsNum)
				{
					return 1;
				}
				else if (xIsHan)
				{
					return -1;
				}
				else if (yIsHan)
				{
					return 1;
				}
				else if (xIsLetter)
				{
					return -1;
				}
				else if (yIsLetter)
				{
					return 1;
				}
				else if (xIsSymbol)
				{
					return -1;
				}
				else if (yIsSymbol)
				{
					return 1;
				}

				return string.Compare(x, y);
			}
		}
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值