【问题标题】:Linq How to combine List Items to other List itemsLinq 如何将列表项与其他列表项组合
【发布时间】:2020-07-14 00:06:50
【问题描述】:

我有多个包含一些项目的字符串列表

想要将每个项目组合在一起,如下所示

        Dim _rsltitm = Nothing
        For Each _itm1 In _lst1
            For Each _itm2 In _lst2
                For Each _itm3 In _lst3
                    _rsltitm &= vbNewLine & _itm1 + _itm2 + _itm3
                Next
            Next
        Next

上面的代码工作正常,但我有超过 8 个列表,有时是 11 个

所以我需要 linq 将多个字符串项列表组合在一起

我正在尝试这样,但我做不到

    Dim _rslt = From itm In _lst1 Select (Function(x) From itm2 In _lst2 Select (Function(d) x & d)) 

【问题讨论】:

  • 你只需要三个循环,不管你有多少列表。您将前两个列表组合成一个列表,然后将其与下一个列表组合以获得另一个列表,然后将其与下一个列表组合,依此类推。内部的两个循环进行组合,最外面的循环遍历所有列表的列表。与任何问题一样,您应该首先手动完成并制定开发算法所涉及的步骤。在代码中实现该算法应该是你做的最后一件事。
  • 一旦你有一个非 LINQ 实现,你大概可以使用 Aggregate 将其转换为 LINQ,尽管我还没有考虑过具体细节。

标签: vb.net list linq


【解决方案1】:

我刚刚测试了这段代码,它似乎做了你想做的事:

Dim list1 As New List(Of String) From {"1", "2", "3"}
Dim list2 As New List(Of String) From {"A", "B", "C"}
Dim list3 As New List(Of String) From {"7", "8", "9"}
Dim list4 As New List(Of String) From {"X", "Y", "Z"}

Dim lists = {list1, list2, list3, list4}

Dim result = lists.Aggregate(Function(current, list)
                                 Dim combinedList As New List(Of String)

                                 For Each prefix In current
                                     combinedList.AddRange(From suffix In list Select prefix & suffix)
                                 Next

                                 Return combinedList
                             End Function)

您只需将所有列表添加到 lists 数组中,result 最终应该包含所需的结果。

我觉得 Lambda 主体应该能够更多地进行 LINQified,但我最初的尝试没有奏效,所以我很快就放弃了。如果你想多花点时间,欢迎你。

编辑:

这是一个函数:

Private Function CombineLists(ParamArray lists As List(Of String)()) As List(Of String)
    Return lists.Aggregate(Function(current, list)
                               Dim combinedList As New List(Of String)

                               For Each prefix In current
                                   combinedList.AddRange(From suffix In list Select prefix & suffix)
                               Next

                               Return combinedList
                           End Function)
End Function

在我的例子中,我可以这样称呼它:

Dim result = CombineLists(list1, list2, list3, list4)

或者像这样:

Dim lists = {list1, list2, list3, list4}

Dim result = CombineLists(lists)

【讨论】:

  • 一切工作都完美加入了 11 个列表并获得了比 Q 更理想的结果.. 非常感谢
  • 我会将这个功能添加到我所有的项目中......非常有用的sn-p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2018-07-15
  • 2014-03-09
  • 1970-01-01
相关资源
最近更新 更多