Search code examples
vb.netlistaddrange

Add Range from one list to another


I have a list(of string) and I search it to get a start and end range, I then need to add that range to a separate list

ex: List A = "a" "ab" "abc" "ba" "bac" "bdb" "cba" "zba"

I need List B to be all the b's (3-5)

What I want to do is ListB.Addrange(ListA(3-5))
How can I accomplish this??


Solution

  • Use List.GetRange()

    Imports System
    Imports System.Collections.Generic
    
    Sub Main()
        '                                               0    1     2      3     4      5      6      7
        Dim ListA As New List(Of String)(New String() {"a", "ab", "abc", "ba", "bac", "bdb", "cba", "zba"})
        Dim ListB As New List(Of String)
    
        ListB.AddRange(ListA.GetRange(3, 3))
        For Each Str As String In ListB
            Console.WriteLine(Str)
        Next
        Console.ReadLine()
    End Sub
    

    or you can use Linq

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    
    Module Module1
        Sub Main()
            '                                               0    1     2      3     4      5      6      7
            Dim ListA As New List(Of String)(New String() {"a", "ab", "abc", "ba", "bac", "bdb", "cba", "zba"})
            Dim ListB As New List(Of String)
    
            ListB.AddRange(ListA.Where(Function(s) s.StartsWith("b")))
            ' This does the same thing as .Where()
            ' ListB.AddRange(ListA.FindAll(Function(s) s.StartsWith("b")))
            For Each Str As String In ListB
                Console.WriteLine(Str)
            Next
            Console.ReadLine()
        End Sub
    End Module
    

    Results:

    enter image description here