【发布时间】:2012-03-26 07:56:58
【问题描述】:
我尝试了几种不同的方法,但似乎无法使用 vb.net 获得我想要的结果。
我有一个字符串数组。 {"55555","44444",""}
我需要一个整数数组 {55555,44444}
这是一个将数组作为参数发送到水晶报表的 wpf 页面。
感谢任何帮助。
【问题讨论】:
标签: vb.net
我尝试了几种不同的方法,但似乎无法使用 vb.net 获得我想要的结果。
我有一个字符串数组。 {"55555","44444",""}
我需要一个整数数组 {55555,44444}
这是一个将数组作为参数发送到水晶报表的 wpf 页面。
感谢任何帮助。
【问题讨论】:
标签: vb.net
你可以使用List(Of T).ConvertAll方法:
Dim stringList = {"123", "456", "789"}.ToList
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))
或与代表一起
Dim intList = stringList.ConvertAll(AddressOf Int32.Parse)
如果你只想使用数组,可以使用Array.ConvertAll method:
Dim stringArray = {"123", "456", "789"}
Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str))
哦,我错过了您的示例数据中的空字符串。然后你需要检查这个:
Dim value As Int32
Dim intArray = (From str In stringArray
Let isInt = Int32.TryParse(str, value)
Where isInt
Select Int32.Parse(str)).ToArray
顺便说一句,这里方法语法一样,丑as always in VB.NET:
Dim intArray = Array.ConvertAll(stringArray,
Function(str) New With {
.IsInt = Int32.TryParse(str, value),
.Value = value
}).Where(Function(result) result.IsInt).
Select(Function(result) result.Value).ToArray
【讨论】:
Dim tempInt% : Dim intA As Int32() = intStrA.Where(Function(x) Int32.TryParse(x, tempInt)).Select(Function(x) tempInt).ToArray()
stringList.ConvertAll(AddressOf Int32.Parse) 在我看来是更清洁的解决方案
您可以使用 Array.ConvertAll 方法:
Dim arrStrings() As String = {"55555", "44444"}
Dim arrIntegers() As Integer = Array.ConvertAll(arrStrings, New Converter(Of String, Integer)(AddressOf ConvertToInteger))
Public Function ConvertToInteger(ByVal input As String) As Integer
Dim output As Integer = 0
Integer.TryParse(input, output)
Return output
End Function
【讨论】:
可能是这样的:
dim ls as new List(of string)()
ls.Add("55555")
ls.Add("44444")
ls.Add(" ")
Dim temp as integer
Dim ls2 as List(Of integer)=ls.Where(function(x) integer.TryParse(x,temp)).Select(function(x) temp).ToList()
【讨论】:
ToArray 而不是ToList。
可能比其他答案多几行代码,但是...
'Example assumes the numbers you are working with are all Integers.
Dim arrNumeric() As Integer
For Each strItemInArray In YourArrayName
If IsNumeric(strItemInArray) Then
If arrNumeric Is Nothing Then
ReDim arrNumeric(0)
arrNumeric(0) = CInt(strItemInArray)
Else
ReDim Preserve arrNumeric(arrNumeric.Length)
arrNumeric(arrNumeric.Length - 1) = CInt(strItemInArray)
End If
End If
Next
【讨论】:
CINT 将抛出 OverflowException,因为对于十进制范围内的值,IsNumeric 也会返回 true。如果值包含 . 也是如此,因为这可以转换为 Double。
我的 $.02
Dim stringList() As String = New String() {"", "123", "456", "789", "a"}
Dim intList() As Integer
intList = (From str As String In stringList
Where Integer.TryParse(str, Nothing)
Select (Integer.Parse(str))).ToArray
【讨论】:
一切都容易多了))
Dim NewIntArray = YouStringArray.Select(Function(x) CInt(x)).ToArray
【讨论】: