0

ラムダの有無にかかわらず、以下を達成する最良の方法は何ですか?

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 に答える