Luis
Luis

Reputation: 5914

Foreach to Linq

I have 2 ForEach loops and I'm trying to convert them into one Linq:

Dim result As Type = Nothing

For Each AssemblyItem As Reflection.Assembly In AppDomain.CurrentDomain.GetAssemblies
    For Each typeItem As Type In AssemblyItem.GetTypes
        If myClass.FullName = typeItem.FullName Then
            result = typeItem
            Exit For
        End If
    Next

    If Not IsNothing(result) Then
        Exit For
    End If
Next

At the moment I have:

result = AppDomain.CurrentDomain.GetAssemblies()
        .ForEach(Sub(x As Reflection.Assembly) 
                     x.GetTypes().ForEach(Sub(t As Type) 
                                              t.FullName = catalogEntity))

I also tried with another approach with no luck:

result = AppDomain.CurrentDomain.GetAssemblies()
        .Select(Sub(x) x.GetTypes()
        .Select(Function(y) y.GetType())
        .Where(Function(z) z.FullName.Equals(catalogEntity.FullName))).FirstOrDefault()

But I'm getting the following error:

Argument not specified for parameter 'action' of 'Public Shared Sub ForEach(Of T)(array() As T, action As System.Action(Of T))'

Any help will be appreciated, thanks in advance!

Upvotes: 0

Views: 1026

Answers (1)

Tim S.
Tim S.

Reputation: 56556

Here it is in VB:

Dim result as Type = AppDomain.CurrentDomain.GetAssemblies().SelectMany(Function(x) x.GetTypes()).FirstOrDefault(Function(x) x.FullName Is myClass.FullName)

And in C# (my native .NET language):

Type result = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).FirstOrDefault(x => x.FullName == myClass.FullName);

Upvotes: 2

Related Questions