Search code examples
c#vb.netc#-to-vb.netcode-conversion

Error Converting C# to VB.NET


I am trying to convert this method to VB.NET but the online converters seem to make a mess of converting it. Can someone help:

C# original:

private IEnumerable<IGrouping<string, Reference>> FindReferencesWithTheSameShortNameButDiffererntFullNames(List<Reference> references)
        {
            return from reference in references
                   group reference by reference.ReferencedAssembly.Name
                       into referenceGroup
                       where referenceGroup.ToList().Select(reference => reference.ReferencedAssembly.FullName).Distinct().Count() > 1
                       select referenceGroup;
        }

VB.NET Using online converter:

Private Function FindReferencesWithTheSameShortNameButDiffererntFullNames(references As List(Of Reference)) As IEnumerable(Of IGrouping(Of String, Reference))
        Return _
            Where referenceGroup.ToList().[Select](Function(reference) reference.ReferencedAssembly.FullName).Distinct().Count() > 1
End Function

This errors on Where is not declared.

I wouldn't have thought that the VB would not be that dis similar to the C# something like this:

Private Function FindReferencesWithTheSameShortNameButDiffererntFullNames(references As List(Of Reference)) As IEnumerable(Of IGrouping(Of String, Reference))
            Return From reference In references
                   Group reference By reference.ReferencedAssembly.Name
                   Into referenceGroup()
                   Where referenceGroup.ToList().Select(Function(reference) ReferencedAssembly.FullName).distinct().count() > 1
                                                        Select referenceGroup

        End Function

But I get: Definition of method referenceGroup is not accessible in this context...can someone help me out?


Solution

  • VB.Net differs slightly in its syntax. The Group keyword also indicates the current grouping and can be used directly or assigned to a named variable.

     Private Function FindReferencesWithTheSameShortNameButDiffererntFullNames(references As List(Of Reference)) As IEnumerable(Of IGrouping(Of String, Reference))
        Return From referenceGroup In references.GroupBy(Of String, Reference)(Function(reference) reference.ReferencedAssembly.Name, Function(reference) reference)
               Where (referenceGroup.ToList().Select(Function(reference) As String
                                                         Return reference.ReferencedAssembly.FullName
                                                     End Function).Distinct().Count() > 1)
               Select referenceGroup
    End Function
    

    Update

    I just noticed you were returning an IGrouping. The query comprehension syntax won't work under that circumstance and you will have to make an explicit call to GroupBy(). The code example has been updated to reflect that.