Lambda Tutorial and Solving a Lambda-Function
Is it possible to shorten the following function to a lambda expression?
Or (to do the trick by myself) what is the best and most understandable for beginners tuto开发者_如何学Gorial for lambda in vb.net?
Function getit(ByVal wert As Integer, ByVal sk As Integer, ByVal list As List(Of Array)) As String
Dim ergebnis As String
ergebnis = "Null"
For Each strg As String() In list
If wert >= Integer.Parse(strg(0)) And wert < Integer.Parse(strg(0)) + 5 And sk = Integer.Parse(strg(1)) Then
Return strg(2)
End If
Next
Return ergebnis
End Function
You could create a lambda expression which takes a string array and return True if it fulfills the condition:
Dim isValidArray = Function(strg as String()) _
wert >= Integer.Parse(strg(0)) AndAlso _
wert < Integer.Parse(strg(0)) + 5 AndAlso _
sk = Integer.Parse(strg(1))
I would also change the signature of your method to accept a list of string array instead of a list of any array. The final code would be:
Function getit(ByVal wert As Integer, ByVal sk As Integer, _
ByVal list As List(Of String())) As String
''//Insert above lambda here
''//Get first valid item or default (Nothing) if no valid item
Dim validArray As String() = list.FirstOrDefault(isValidArray)
If validArray IsNot Nothing
Return validArray(2)
Else
Return "Null"
End If
End Function
Give this a try:
Dim getit As String;
getit = (From x In list
Where (wert >= Integer.Parse(x(0))) AndAlso (wert < Integer.Parse(x(0)) + 5) AndAlso (sk = Integer.Parse(x(1)))
Select x(2)).Union(Of String)(New List(Of String) { "Null" }).First(Of String)()
精彩评论