Reputation: 304
I have multiple list of string with some items
want to combine every items together like below
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
above code is working fine but i have more than 8 lists or sometimes 11
so i need linq to combine multiple list of string items together
i am trying like this but i could not
Dim _rslt = From itm In _lst1 Select (Function(x) From itm2 In _lst2 Select (Function(d) x & d))
Upvotes: 1
Views: 145
Reputation: 54417
I just tested this code and it seems to do what you want:
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)
You just add all your lists to that lists
array and result
should end up containing the desired result.
I feel like that Lambda body should be able to be LINQified a bit more but my initial attempts didn't work so I gave up quickly. If you want to put some more time into it, you're welcome to.
EDIT:
Here's that in a function:
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
In my example, I could either call that like so:
Dim result = CombineLists(list1, list2, list3, list4)
or like so:
Dim lists = {list1, list2, list3, list4}
Dim result = CombineLists(lists)
Upvotes: 2