Tony L.
Tony L.

Reputation: 19506

How to return a List(Of String) from a LINQ statement with a Group By in VB.net?

I've seen several questions on how to do this in C# but I'm having trouble translating those to VB. Here's the basics of my issue:

This works but I'm guessing there's a better way to do it without iterating through the list:

Public Function GetGroups() As IEnumerable(Of String)
    Dim GroupList As New List(Of String)

    Dim CodeList = (From c In Context.Codes
                    Group c.Group By c.Group Into g = Group)

    For Each c In CodeList
        GroupList.Add(c.Group)
    Next

    Return GroupList
End Function

What I seem to be struggling with the most is using Group By in LINQ. I'm guessing this could probably be done in 1 or 2 lines by having LINQ return just the list of strings or by converting the list of anonymous objects to a list of strings.

Upvotes: 0

Views: 2142

Answers (1)

pseudocoder
pseudocoder

Reputation: 4402

Well, if you don't need anything in the group, you can just use .Distinct():

Return (
    From c In Context.Codes
    Order By c.Group
    Select c.Group
).Distinct().ToList()

Edit: Added Order By

Upvotes: 3

Related Questions