将字符串数组转换为int数组

Pri*_*ime 17 vb.net

我尝试了几种不同的方法,似乎无法使用vb.net得到我想要的结果.

我有一个字符串数组.{"55555","44444",""}

我需要一个整数数组{55555,44444}

这是一个将数组作为参数发送到晶体报告的wpf页面.

任何帮助表示赞赏.

Tim*_*ter 38

您可以使用以下List(Of T).ConvertAll方法:

Dim stringList = {"123", "456", "789"}.ToList
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))
Run Code Online (Sandbox Code Playgroud)

或与代表

Dim intList = stringList.ConvertAll(AddressOf Int32.Parse)
Run Code Online (Sandbox Code Playgroud)

如果您只想使用Arrays,可以使用Array.ConvertAll method:

Dim stringArray = {"123", "456", "789"}
Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str))
Run Code Online (Sandbox Code Playgroud)

哦,我错过了样本数据中的空字符串.然后你需要检查一下:

Dim value As Int32
Dim intArray = (From str In stringArray
               Let isInt = Int32.TryParse(str, value)
               Where isInt
               Select Int32.Parse(str)).ToArray
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这里的方法语法是一样的,丑陋的一如既往的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
Run Code Online (Sandbox Code Playgroud)