0

What is the best way of achieving the following with and without lamdas please

Module Module1

    Sub Main()

        Dim countries As New List(Of Country)
        countries.Add(New Country("Africa"))
        countries.Add(New Country("India"))
        countries.Add(New Country("China"))
        countries.Add(New Country("Belgium"))

        Dim newCountry As String = "Spain"

        If Not countries.Exists(newCountry) Then
            countries.Add(New Country(newCountry))
        End If

    End Sub
End Module


Public Class Country

    Public Name As String

    Public Sub New(name As String)
        Me.Name = name
    End Sub

End Class
4

1 回答 1

1

应该再努力一点!!

Module Module1

    Dim newCountry As String = "Spain"

    Sub Main()

        Dim countries As New List(Of Country)
        countries.Add(New Country("Africa"))
        countries.Add(New Country("India"))
        countries.Add(New Country("China"))
        countries.Add(New Country("Belgium"))

        ' Long Hand
        Dim pred As New Predicate(Of Country)(AddressOf CountryExists)
        If Not countries.Exists(pred) Then
            countries.Add(New Country(newCountry))
        End If

        ' Using Lamda
        If Not countries.Exists(Function(c As Country) c.Name = newCountry) Then
            countries.Add(New Country(newCountry))
        End If

        ' Check
        For Each c As Country In countries
            Console.WriteLine(c.Name)
        Next
        Console.ReadLine()
    End Sub

    Private Function CountryExists(ByVal country As Country)
        Return country.Name = newCountry
    End Function

End Module


Public Class Country

    Public Name As String

    Public Sub New(name As String)
        Me.Name = name
    End Sub

End Class
于 2013-01-05T13:36:51.333 回答