我有一个字符串"2-6,8,10-15,20-23"
我需要将其转换为数组中完全填充的数字范围,如下所示:
{2,3,4,5,6,8,10,11,12,13,14,15,20,21,22,23}
你有任何想法如何转换它?
Mark Heath 在 PluralSight 有一个关于 LINQ 的课程很好地解决了这个问题。使用 LINQ,您可以使用下面显示的示例快速完成此操作。
string value = "7-10,2,5,12,17-18";
var result = value.Split(',')
.Select(x => x.Split('-'))
.Select(p => new { First = int.Parse(p.First()), Last = int.Parse(p.Last()) })
.SelectMany(x => Enumerable.Range(x.First, x.Last - x.First + 1))
.OrderBy(z=>z);
从Split
字符串中创建一个数组。第一个Select
创建一个数组,每个数组有 1 个或 2 个元素。第二个Select
创建一个匿名类型,指示基于数组值的起始值和结束值。SelectMany
使用该方法Enumerable.Range
从每个匿名对象创建一系列数字,然后将其展平IEnumerable
为整数集合。最后,OrderBy
将数字用于报告和其他用途。
这段代码应该可以解决问题(该过程在注释中描述):
Dim s As String = "2-6,8,10-15,20-23" 'Your values
Dim values As New List(Of Integer)() 'Create an List of Integer values / numbers
For Each value As String In s.Split(","C) ' Go through each string between a comma
If value.Contains("-"C) Then 'If this string contains a hyphen
Dim begin As Integer = Convert.ToInt32(value.Split("-"C)(0)) 'split it to get the beginning value (in the first case 2)
Dim [end] As Integer = Convert.ToInt32(value.Split("-"C)(1)) ' and to get the ending value (in the first case 6)
For i As Integer = begin To [end] 'Then fill the integer List with values
values.Add(i)
Next
Else
values.Add(Convert.ToInt32(value)) 'If the text doesn't contain a hyphen, simply add the value to the integer List
End If
Next
string numberString = "2-6,8,10-15,20-23";
List<int> cNumberString = getValidString(numberString);
List<int> getValidString(string str)
{
List<int> lstNumber = new List<int>();
string[] cNumberArray = str.Split(',');
for (int k = 0; k < cNumberArray.Length; k++)
{
string tmpDigit = cNumberArray[k];
if (tmpDigit.Contains("-"))
{
int start = int.Parse(tmpDigit.Split('-')[0].ToString());
int end = int.Parse(tmpDigit.Split('-')[1]);
for (int j = start; j <= end; j++)
{
if (!lstNumber.Contains(j))
lstNumber.Add(j);
}
}
else
{
lstNumber.Add(int.Parse(tmpDigit));
}
}
return lstNumber;
}
假设您的输入字符串总是会被正确格式化,您可以尝试这样的事情:
Public Function GetIntArray(input As String) As Integer()
Dim splits() = input.Split(",")
Dim result As New List(Of Integer)
For Each s In splits
If s.Contains("-") Then
Dim low As Integer = s.Split("-")(0)
Dim hi As Integer = s.Split("-")(1)
For i = low To hi
result.Add(i)
Next
Else
result.Add(s)
End If
Next
Return result.ToArray
End Function
基本思想是沿逗号分隔符拆分输入字符串,然后检查该字符串是单个数字还是具有范围。
Dim stringArray = {"123", "456", "789"}
Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str))