none
Arrays RRS feed

  • Question

  • I have a for each loop that returns a string on each pass. I would like to find the best way to put the result into an array For testing I am writing the results to a text file (errorlog)

                   For Each retunedLicence In LicenceCollection.Entities
                        Globals.clsGlobals.WrtietoErrorLog(retunedLicence.GetAttributeValue(Of EntityReference)("new__licenceid").Id.ToString)
                    Next
    If there are 3 items then Im presuming the array would contain 3 elements 0,1,2 if four items then 0,1,2,3  but I don't know how to work it so that there a no empty elements, ie if three items I don't want an array 0,1,2,3 with 0 being empty 


    Dont ask me .. i dont know

    Tuesday, April 9, 2019 1:40 PM

Answers

  • Hello,

    If the array simply needs to be split then converted to an Integer array where you are sure that the array elements are always able to convert to Integers then this will work but non-integer values will be represented as 0.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Values As String = "0,1,2,3"
            Dim valueArray As String() = Values.Split(","c)
    
            Dim results = Array.ConvertAll(valueArray,
               Function(item)
                   Dim tempValue As Integer
                   Return Integer.TryParse(item, tempValue)
               End Function)
        End Sub
    End Class
    

    This will throw an exception if one or more elements are not integers

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim stringArray = {"1", "2", "3"}
            Dim intList = stringArray.
                    ToList().
                    ConvertAll(Function(stringValue) Integer.Parse(stringValue))
        End Sub
    End Class
    

    If you would like to check for valid integers first

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim testValue As Integer
            Dim stringArray = {"1", "2", "3"}
    
            If stringArray.All(Function(input) Integer.TryParse(input, testValue)) Then
                Console.WriteLine("Safe to perform conversion")
            Else
                Console.WriteLine("Not safe to perform conversion")
            End If
        End Sub
    End Class
    

    This can be wrapped in a function

    Public Module ArrayHelpers
        Public Function CanConvertToIntegerArray(sender() As String) As Boolean
            Dim testValue As Integer
            Return sender.All(Function(input) Integer.TryParse(input, testValue))
        End Function
    End Module

    If using Framework 3.5 or higher use my extensions/

    Public Module Extensions
        ''' <summary>
        ''' Given a string array assumed to be all integers return
        ''' only those elements which are integers. If the string
        ''' array had five elements and only two elements could be
        ''' converted the length of the returning array will be a
        ''' length of 2.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <returns></returns>
        <Runtime.CompilerServices.Extension>
        Public Function ToIntegerArray(sender() As String) As Integer()
            Return Array.ConvertAll(sender,
                                    Function(input)
                                        Dim value As Integer
                                        Return New With
                                       {
                                       .IsInteger = Integer.TryParse(input, value),
                                       .Value = value
                                       }
                                    End Function).
                Where(Function(result) result.IsInteger).
                Select(Function(result) result.Value).
                ToArray()
        End Function
        ''' <summary>
        ''' Given a string array assumed to be all integers return
        ''' all elements no matter if they can be converted. Non integer
        ''' values are returned as 0.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <returns></returns>
        <Runtime.CompilerServices.Extension>
        Public Function ToIntegerPreserveArray(sender() As String) As Integer()
            Return Array.ConvertAll(sender,
                                    Function(input)
                                        Dim integerValue As Integer
                                        Integer.TryParse(input, integerValue)
                                        Return integerValue
                                    End Function)
        End Function
    
    End Module

    In the following the first call returns only two elements while the second uses 0 for unconvertable value middle element

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim stringArray As String() = {"1", "A2", "3"}
    
            Dim intArray1 = stringArray.ToIntegerArray()
            Dim intArray2 = stringArray.ToIntegerPreserveArray()
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:23 PM
    Tuesday, April 9, 2019 2:30 PM
    Moderator
  • I am not sure I understand what you are asking but if I do then the following should work.

    Shared Sub vbArray()
    	Dim sa() As String = { "One", "Two", "", "Four" }
    	Dim sl As New List(Of String)()
    	For Each s As String In sa
    		If s.Length > 0 Then
    			sl.Add(s)
    		End If
    	Next s
    	Dim newsa() As String = sl.ToArray()
    End Sub
    

    That uses a list to dynamically create just the items that are not empty. The list can be converted back to an array if necessary.



    Sam Hobbs
    SimpleSamples.Info

    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:22 PM
    Tuesday, April 9, 2019 4:28 PM
  • Hi

    Here is some code that shows 3 different ways to get a full array without 'extra' items at the end, depending on whether or not you know in advance of the numberr of strings you will be using .

    Arrays are very 'messy' with memory, so using one method over the other can prevent wasting large chunks of memory.

    Option Strict On
    Option Explicit On
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Dim array1(99999) As String
            Dim items1 As Integer = 19
    
            For i As Integer = 0 To items1
                array1(i) = i.ToString
            Next
            ReDim Preserve array1(items1)
    
            ' OR ................
    
            Dim array2() As String
            Dim items2 As Integer = 19
    
            ReDim array2(items2)
            For i As Integer = 0 To items2
                array2(i) = i.ToString
            Next
    
            ' OR ................
    
            Dim rand As New Random
            Dim array3() As String
            Dim items3 As Integer = rand.Next(9, 20)
    
            For i As Integer = 0 To items3
                ReDim Preserve array3(items3)
                array3(i) = i.ToString
            Next
    
        End Sub
    End Class



    Regards Les, Livingston, Scotland



    • Edited by leshay Tuesday, April 9, 2019 4:47 PM
    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:22 PM
    Tuesday, April 9, 2019 4:40 PM
  • I have a for each loop that returns a string on each pass. I would like to find the best way to put the result into an array For testing I am writing the results to a text file (errorlog)

                   For Each retunedLicence In LicenceCollection.Entities
                        Globals.clsGlobals.WrtietoErrorLog(retunedLicence.GetAttributeValue(Of EntityReference)("new__licenceid").Id.ToString)
                    Next
    If there are 3 items then Im presuming the array would contain 3 elements 0,1,2 if four items then 0,1,2,3  but I don't know how to work it so that there a no empty elements, ie if three items I don't want an array 0,1,2,3 with 0 being empty 


    Dont ask me .. i dont know

    The best way for this with strings as you ask? The price of some spend bytes in memory. Most computers have at least more bytes available than the sum of the text of all bibles in the world contain. 

    Probably you have no chance to get back the memory you use to do what you want with the code which also needs room.

    It is a 1955 problem. Currently in the same order as "What is the best solution to check if the lamp in the refrigerator is not burning with the closed door."



    Success
    Cor


    • Edited by Cor Ligthert Tuesday, April 9, 2019 5:21 PM
    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:22 PM
    Tuesday, April 9, 2019 5:20 PM

All replies

  • Hello,

    If the array simply needs to be split then converted to an Integer array where you are sure that the array elements are always able to convert to Integers then this will work but non-integer values will be represented as 0.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Values As String = "0,1,2,3"
            Dim valueArray As String() = Values.Split(","c)
    
            Dim results = Array.ConvertAll(valueArray,
               Function(item)
                   Dim tempValue As Integer
                   Return Integer.TryParse(item, tempValue)
               End Function)
        End Sub
    End Class
    

    This will throw an exception if one or more elements are not integers

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim stringArray = {"1", "2", "3"}
            Dim intList = stringArray.
                    ToList().
                    ConvertAll(Function(stringValue) Integer.Parse(stringValue))
        End Sub
    End Class
    

    If you would like to check for valid integers first

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim testValue As Integer
            Dim stringArray = {"1", "2", "3"}
    
            If stringArray.All(Function(input) Integer.TryParse(input, testValue)) Then
                Console.WriteLine("Safe to perform conversion")
            Else
                Console.WriteLine("Not safe to perform conversion")
            End If
        End Sub
    End Class
    

    This can be wrapped in a function

    Public Module ArrayHelpers
        Public Function CanConvertToIntegerArray(sender() As String) As Boolean
            Dim testValue As Integer
            Return sender.All(Function(input) Integer.TryParse(input, testValue))
        End Function
    End Module

    If using Framework 3.5 or higher use my extensions/

    Public Module Extensions
        ''' <summary>
        ''' Given a string array assumed to be all integers return
        ''' only those elements which are integers. If the string
        ''' array had five elements and only two elements could be
        ''' converted the length of the returning array will be a
        ''' length of 2.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <returns></returns>
        <Runtime.CompilerServices.Extension>
        Public Function ToIntegerArray(sender() As String) As Integer()
            Return Array.ConvertAll(sender,
                                    Function(input)
                                        Dim value As Integer
                                        Return New With
                                       {
                                       .IsInteger = Integer.TryParse(input, value),
                                       .Value = value
                                       }
                                    End Function).
                Where(Function(result) result.IsInteger).
                Select(Function(result) result.Value).
                ToArray()
        End Function
        ''' <summary>
        ''' Given a string array assumed to be all integers return
        ''' all elements no matter if they can be converted. Non integer
        ''' values are returned as 0.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <returns></returns>
        <Runtime.CompilerServices.Extension>
        Public Function ToIntegerPreserveArray(sender() As String) As Integer()
            Return Array.ConvertAll(sender,
                                    Function(input)
                                        Dim integerValue As Integer
                                        Integer.TryParse(input, integerValue)
                                        Return integerValue
                                    End Function)
        End Function
    
    End Module

    In the following the first call returns only two elements while the second uses 0 for unconvertable value middle element

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim stringArray As String() = {"1", "A2", "3"}
    
            Dim intArray1 = stringArray.ToIntegerArray()
            Dim intArray2 = stringArray.ToIntegerPreserveArray()
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:23 PM
    Tuesday, April 9, 2019 2:30 PM
    Moderator
  • I am not sure I understand what you are asking but if I do then the following should work.

    Shared Sub vbArray()
    	Dim sa() As String = { "One", "Two", "", "Four" }
    	Dim sl As New List(Of String)()
    	For Each s As String In sa
    		If s.Length > 0 Then
    			sl.Add(s)
    		End If
    	Next s
    	Dim newsa() As String = sl.ToArray()
    End Sub
    

    That uses a list to dynamically create just the items that are not empty. The list can be converted back to an array if necessary.



    Sam Hobbs
    SimpleSamples.Info

    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:22 PM
    Tuesday, April 9, 2019 4:28 PM
  • Hi

    Here is some code that shows 3 different ways to get a full array without 'extra' items at the end, depending on whether or not you know in advance of the numberr of strings you will be using .

    Arrays are very 'messy' with memory, so using one method over the other can prevent wasting large chunks of memory.

    Option Strict On
    Option Explicit On
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Dim array1(99999) As String
            Dim items1 As Integer = 19
    
            For i As Integer = 0 To items1
                array1(i) = i.ToString
            Next
            ReDim Preserve array1(items1)
    
            ' OR ................
    
            Dim array2() As String
            Dim items2 As Integer = 19
    
            ReDim array2(items2)
            For i As Integer = 0 To items2
                array2(i) = i.ToString
            Next
    
            ' OR ................
    
            Dim rand As New Random
            Dim array3() As String
            Dim items3 As Integer = rand.Next(9, 20)
    
            For i As Integer = 0 To items3
                ReDim Preserve array3(items3)
                array3(i) = i.ToString
            Next
    
        End Sub
    End Class



    Regards Les, Livingston, Scotland



    • Edited by leshay Tuesday, April 9, 2019 4:47 PM
    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:22 PM
    Tuesday, April 9, 2019 4:40 PM
  • I have a for each loop that returns a string on each pass. I would like to find the best way to put the result into an array For testing I am writing the results to a text file (errorlog)

                   For Each retunedLicence In LicenceCollection.Entities
                        Globals.clsGlobals.WrtietoErrorLog(retunedLicence.GetAttributeValue(Of EntityReference)("new__licenceid").Id.ToString)
                    Next
    If there are 3 items then Im presuming the array would contain 3 elements 0,1,2 if four items then 0,1,2,3  but I don't know how to work it so that there a no empty elements, ie if three items I don't want an array 0,1,2,3 with 0 being empty 


    Dont ask me .. i dont know

    The best way for this with strings as you ask? The price of some spend bytes in memory. Most computers have at least more bytes available than the sum of the text of all bibles in the world contain. 

    Probably you have no chance to get back the memory you use to do what you want with the code which also needs room.

    It is a 1955 problem. Currently in the same order as "What is the best solution to check if the lamp in the refrigerator is not burning with the closed door."



    Success
    Cor


    • Edited by Cor Ligthert Tuesday, April 9, 2019 5:21 PM
    • Marked as answer by Pete Newman Tuesday, April 9, 2019 5:22 PM
    Tuesday, April 9, 2019 5:20 PM