Share via

Copy List Of String to another List Of String

StewartBW 1,905 Reputation points
2024-06-13T14:51:58.8366667+00:00

Hello

I need to know the difference between the 3 paths to my goal:

Dim MyList as New List(Of String)
MyList.Add(str1) ... and so on ...

Dim NewList As New List(Of String)

Now I have 3 ways:

1 NewList.AddRange(ResumeFailed)
2 NewList.AddRange(ResumeFailed.ToList)
3 NewList.AddRange(ResumeFailed.ToArray)

Thanks :)

Developer technologies | VB
0 comments No comments

Answer accepted by question author
  1. KOZ6.0 6,810 Reputation points
    2024-06-13T16:00:02.8566667+00:00
    '1 NewList.AddRange(ResumeFailed)
    NewList.AddRange(ResumeFailed)
    
    '2 NewList.AddRange(ResumeFailed.ToList)   
    Dim list As List(Of String) = ResumeFailed.ToList() ' System.Linq Extension Methods
    NewList.AddRange(list)
    
    '3 NewList.AddRange(ResumeFailed.ToArray)
    Dim array As String() = ResumeFailed.ToArray()      ' List<T>.ToArray
    NewList.AddRange(array)
    

    The fastest are 1, 3, and 2. But the fastest one is:

    '4 new NewList(ResumeFailed)
    Dim NewList As New List(Of String)(ResumeFailed)
    

    This is a sample to measure performance.Please try running it.

    Module Program
    
        Sub Main()
    
            Const count As Integer = 100000
            Dim MyList As New List(Of String)
            MyList.AddRange(Enumerable.Repeat("AAAA", 10000))
    
            Watch("1 NewList.AddRange(MyList)",
                  Sub()
                      Dim tmp As New List(Of String)
                      tmp.AddRange(MyList)
                  End Sub, count)
            Watch("2 NewList.AddRange(MyList.ToList)",
                  Sub()
                      Dim tmp As New List(Of String)
                      tmp.AddRange(MyList.ToList)
                  End Sub, count)
            Watch("3 NewList.AddRange(MyList.ToArray)",
                  Sub()
                      Dim tmp As New List(Of String)
                      tmp.AddRange(MyList.ToArray)
                  End Sub, count)
            Watch("4 new NewList(MyList)",
                  Sub()
                      Dim tmp As New List(Of String)(MyList)
                  End Sub, count)
    
        End Sub
    
        Sub Watch(msg As String, action As Action, count As Integer)
            Dim sw As New Stopwatch()
            sw.Start()
            For i = 1 To count
                action.Invoke()
            Next
            sw.Stop()
            Console.WriteLine($"{msg.PadRight(40)} : {sw.Elapsed}")
        End Sub
    
    End Module
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.