Copy List Of String to another List Of String

StewartBW 1,145 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 :)

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,737 questions
0 comments No comments
{count} votes

Accepted answer
  1. KOZ6.0 6,490 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 Answers by the question author, which helps users to know the answer solved the author's problem.