我正在使用c#,.net 4.7
我有3个字符串,即。
[test.1, test.10, test.2]
我需要对它们进行分类以获取:
test.1
test.2
test.10
我可能会得到其他字符串,例如
[1test, 10test, 2test]
应该产生:
1test
2test
10test
使用相同的方法。
想法?
预先感谢。
您可以使用Regex使用分析数字,然后对字符串进行排序。例如,
Regex re = new Regex(@"d+");
var result = strArray.Where(x=>re.Match(x).Success)
.Select(x=> new { Key = int.Parse(re.Match(x).Value),Value = x})
.OrderBy(x=>x.Key).Select(x=>x.Value);
strarray是字符串的集合。
请注意,在上面的情况下,您忽略了没有数字零件的字符串(如OP中没有描述(。字符串的数字部分是使用REGEX解析的,然后将其用于对集合进行排序。
示例,输入
var strArray = new string[]{"1test", "10test", "2test"};
输出
1test
2test
10test
输入
var strArray = new string[]{"test.1", "test.10", "test.2"};
Outpuyt
test.1
test.2
test.10
对于您的第一个数组,您可以做
var array = new[] { "test.1", "test.10", "test.2" };
var sortedArray = array.OrderBy(s => int.Parse(s.Substring(5, s.Length - 5)));
第二个数组
var array = new[] { "1test", "2test", "10test" };
var sortedArray = array.OrderBy(s => int.Parse(s.Substring(0, s.Length - 4)));
尝试此代码。它使用sortedDictionary始终将其插入时按键进行排序。
static void Main(string[] args)
{
SortedDictionary<int, string> tuples = new SortedDictionary<int, string>();
string[] stringsToSortByNumbers = { "test.1", "test.10", "test.2" };
foreach (var item in stringsToSortByNumbers)
{
int numeric = Convert.ToInt32(new String(item.Where(Char.IsDigit).ToArray()));
tuples.Add(numeric, item);
}
foreach (var item in tuples)
{
Console.WriteLine(item.Value);
}
Console.ReadKey();
}