使用For Each循环存储的数组列表

时间:2014-03-26 06:27:28

标签: vb.net loops foreach

我想存储" zone_check_value"到一个字符串数组然后插入数组我会检查字符串数组,如果下一个值重复或重复。

实施例

1st Example
    1st loop = zone_check_value = ZD1/01/2014
    2nd loop = zone_check_value = ZD1/01/2014
2nd Example
    1st loop = zone_check_value = ZD1/01/2014
    2nd loop = zone_check_value = ZD2/02/2014
    3rd loop = zone_check_value = ZD1/01/2014

代码:

 For Each dt As DataTable In xls.Tables
   Dim array_of_string as String() 'i want to put the value in here
    For Each dr As DataRow In dt.Rows
        Dim zone_destination As String = dr(2).ToString
        Dim affected_date As String = dr(7).ToString
        Dim zone_check_value = zone_destination + affected_date
        ''''''How can i store zone_check_value in a string array?
    Next
Next

修改

如果我在循环中添加select case怎么办? array_of_string值变为NULL。我需要检查array_of_string中当前值的值。

示例代码

 For Each dt As DataTable In xls.Tables
   Dim array_of_string as String() 'i want to put the value in here
   select Case dt.tablename
    case "Sheet1"
      For Each dr As DataRow In dt.Rows
        Dim zone_destination As String = dr(2).ToString
        Dim affected_date As String = dr(7).ToString
        Dim zone_check_value = zone_destination + affected_date
        ''''''How can i store zone_check_value in a string array?
      Next
    case "Sheet 2"
      For Each dr As DataRow In dt.Rows
         Dim check_value as Boolean = array_of_string.Contains(dr(0).ToString)
         'but when i got in sheet 2 the array_of_string is null
      Next
Next

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用List(Of String)

For Each dt As DataTable In xls.Tables
   Dim array_of_string as List(Of String) = New List(Of String) 'i want to put the value in here
    For Each dr As DataRow In dt.Rows
        Dim zone_destination As String = dr(2).ToString
        Dim affected_date As String = dr(7).ToString
        Dim zone_check_value = zone_destination & affected_date
        ''''''How can i store zone_check_value in a string array?
        array_of_string.Add(zone_check_value)
    Next
    ''' Now if you really need it in array form you can cast it via:
    ''' Dim values() As String = array_of_string.ToArray()
Next

您甚至可以考虑:

For Each dt As DataTable In xls.Tables
  Dim values As List(Of String) = New List(Of String)
  dt.Rows.ForEach( Sub(item) values.Add(item(2).ToString & item(7).ToString) )
  ''' Now do something with values.
Next

无论哪种方式,请确保始终使用字符串连接运算符& 来连接字符串。如果在字符串上使用算术加法运算符 + 会不时给您带来问题。