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

时间:2015-07-31 19:26:39

标签: vb.net linq

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:

  • Table of data NOT normalized and accessed via Entity Framework
  • Get all unique string values in a certain field
  • Convert those values to a List(Of String)

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.

1 个答案:

答案 0 :(得分:3)

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