在有和没有lamdas的情况下实现以下目标的最佳方式是
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
答案 0 :(得分: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