将字符串数组转换为 int 数组 [英] Convert string array to int array

查看:129
本文介绍了将字符串数组转换为 int 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have tried a couple different ways and cannot seem to get the result I want using vb.net.

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

I have an array of strings. {"55555 ","44444", " "}

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

I need an array of integers {55555,44444}

这是一个 wpf 页面,将数组作为参数发送给水晶报告.

This is a wpf page that is sending the array as a parameter to a crystal report.

感谢任何帮助.

推荐答案

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

You can use the List(Of T).ConvertAll method:

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

或与委托人

Dim intList = stringList.ConvertAll(AddressOf Int32.Parse)

如果您只想使用数组,则可以使用 Array.ConvertAll 方法:

If you only want to use Arrays, you can use the Array.ConvertAll method:

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

哦,我错过了您的示例数据中的空字符串.然后你需要检查这个:

Oh, i've missed the empty string in your sample data. Then you need to check this:

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

顺便说一下,这里的方法语法是一样的,丑陋的在 VB.NET 中一如既往:

By the way, here's the same in method syntax, ugly 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

这篇关于将字符串数组转换为 int 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆