ElektroStudios
ElektroStudios

Reputation: 20474

Generic function to merge multiple lists

In C# or VBNET How I could write a generic function to join two (or more) lists in a NEW unique list?

I've seen the Join method of a list type but I have no idea of how to use it, also I don't know if it can join more than 1 list at a time (that's why I asked for a generic function if Join method can't do the job).

Something like this:

private function JoinLists(of T)(byval Lists() as list(of T)) as list(of T)

    dim newlist as new list(of T)

    ' some LINQ method or a For + list.Join()...

    return joinedlists

end function

UPDATE:

I'm trying to use Anders Abel suggestion but this does not work:

Private Function JoinLists(Of T)(ByVal Lists() As List(Of T)) As List(Of T)

    Dim newlist As New list(Of T)

    For Each l As List(Of T) In Lists
        newlist.Concat(l)
    Next

    Return newlist

End Function

    Dim a As New List(Of String) From {"a", "b"}
    Dim b As New List(Of String) From {"f", "d"}

    Dim newlist As List(Of String) = JoinLists(Of String)({a, b})

    MsgBox(newlist.Count) ' Result: 0  Expected: 3

    For Each item In newlist
        MsgBox(item) ' Any item is shown
        'expected:
        'a
        'b
        'f
        'd
    Next

Upvotes: 0

Views: 222

Answers (1)

Anders Abel
Anders Abel

Reputation: 69270

I assume that you don't want to do a join in the sense as SQL joins, but rather create a new sequence which contains all the elements from either list, but without duplicates. That can be done with linq (C# syntax):

return list1.Concat(list2).Distinct();

Edit

If the source is a collection of collections, SelectMany can be used to flatten it into one sequence:

In C# syntax the JoinList function would contain:

return lists.SelectMany(i => i).Distinct().ToList;

Upvotes: 1

Related Questions