【问题标题】:List(Of String) into List(Of integer) with Splitting in VB.NetList(Of String) 到 List(Of integer) 与 VB.Net 中的拆分
【发布时间】:2020-11-20 17:22:55
【问题描述】:

我有一个字符串列表:

Dim values as List(Of String) = {{1 ; 4} , {2 ; 8} , {3 ; 16}}

这个列表是由以前的现有代码创建的(所以我没有自己将其定义为字符串列表)。

所以当我输入时

MsgBox(values(0))
'Output: 1 ; 4

这出现了。

那些值对应xy-Values,所以我想要的是这样的

MsgBox(xVal(0))
'Output: 1
MsgBox(yVal(2))
'Output: 16

我一直在寻找解决方案已经有一段时间了,因为 VB.net 对我来说很新。这里的主要问题是类型之间的转换。任何形式的帮助都将不胜感激,谢谢。

【问题讨论】:

    标签: arrays vb.net list


    【解决方案1】:

    这些值对应于 xy 值

    这是一个使用ConvertAll 获得ListPoint 的示例:

    Dim values As New List(Of String)({"1 ; 4", "2 ; 8", "3 ; 16"})
    Dim coords As List(Of Point) = values.ConvertAll(Of Point)(Function(ByVal input As String)
                                                                   Dim data() As String = input.Split(";")
                                                                   Return New Point(CInt(data(0)), CInt(data(1)))
                                                               End Function)
    For Each pt As Point In coords
        Debug.Print(pt.X & ", " & pt.Y)
    Next
    

    输出:

    1, 4
    2, 8
    3, 16
    

    我没有对数据进行任何错误检查。它假设每个字符串都有一个分号,并且结果数组的前两个位置的元素是有效的整数。

    【讨论】:

      【解决方案2】:

      您可以将列表转换为 x, y 数组,如下所示

      Dim xval as new List(Of Integer)
      Dim yVal as new List(Of Integer)
      For Each v in values
          xval.add(v.Split(";")(0))
          yval.add(v.Split(";")(1))
      Next
      ' Prinitng as you tested, 
      Console.WriteLine(xval(0))
      Console.WriteLine(yval(2))
      

      您可以使用 xVal、yVal 数组来处理您的业务逻辑

      【讨论】:

      • 谢谢!首先,它对我不起作用。但是当我将 xVal 和 yVal 更改为对象列表时,一切都很好。否则无论出于何种原因,它都会显示“System.OverflowException”
      【解决方案3】:

      你可以使用拆分功能:

      MsgBox(values(0).Split(";")(0).Trim) 'For the X in values(0)
      MsgBox(values(0).Split(";")(1).Trim) 'For the Y in values(0)
      

      Split(";") 将使用“;”将字符串拆分为数组作为分隔符。

      https://docs.microsoft.com/fr-fr/dotnet/api/microsoft.visualbasic.strings.split?view=net-5.0

      Trim 用于去除空格:

      Dim a_string as string = " 7 "
      MsgBox(a_string.Trim) 'Output : "7"
      

      在你的例子中:

      MsgBox(values(0).Split(";")(0).Trim)
      'Output: 1
      MsgBox(values(2).Split(";")(1).Trim)
      'Output: 16
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多