将一个列表的范围添加到另一个列表

4
我有一个字符串列表 list(of string),我想要从中搜索一个起始和结束范围,并将该范围添加到另一个列表中。例如,给出列表 A = "a" "ab" "abc" "ba" "bac" "bdb" "cba" "zba",我需要在列表 B 中找到所有 b 的项(3-5)。我希望实现的功能是ListB.AddRange(ListA(3-5))。您可以通过以下方式完成这个任务:

1
搜索关键字是: .FindAll.CopyTo - Top Systems
1个回答

10

使用 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

或者你可以使用 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

结果:

图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接