VB.Net/LINQ/Lambda

Материал из VB Эксперт
Перейти к: навигация, поиск

Lambda expression syntax

<source lang="vbnet"> Option Strict On Imports System.Collections.Generic Module Program

 Sub Main()
   Dim list As New List(Of Integer)()
   list.AddRange(New Integer() {20, 1, 4, 8, 9, 44})
   Dim evenNumbers As List(Of Integer) = list.FindAll(Function(i As Integer) (i Mod 2) = 0)
   For Each evenNumber As Integer In evenNumbers
     Console.WriteLine(evenNumber)
   Next
 End Sub
 Function IsEvenNumber(ByVal i As Integer) As Boolean
   Return (i Mod 2) = 0
 End Function
 Sub LambdaExpressionSyntax()
 End Sub

End Module


 </source>


Lambdas with Multiple Params

<source lang="vbnet">

Option Strict On Public Delegate Function BinaryOp(ByVal x As Integer, ByVal y As Integer) As Integer Public Class SimpleMath

 Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
   Return x + y
 End Function
 Public Function Subtract(ByVal x As Integer, _
   ByVal y As Integer) As Integer
   Return x - y
 End Function

End Class Module Program

 Sub Main()
   Dim b As New BinaryOp(Function(x, y) x + y)
   DisplayDelegateInfo(b)
   Console.WriteLine(b(10, 10))
 End Sub
 Sub DisplayDelegateInfo(ByVal delObj As System.Delegate)
   For Each d As System.Delegate In delObj.GetInvocationList()
     Console.WriteLine("Method Name: {0}", d.Method)
     Console.WriteLine("Type Name: {0}", d.Target)
   Next
 End Sub

End Module


 </source>


Lambda with No Args

<source lang="vbnet"> Option Strict On Public Delegate Function GetTime() As String Module Test

 Sub Main()
   Dim t As New GetTime(Function() DateTime.Now.ToString())
   Console.WriteLine(t)
 End Sub

End Module


 </source>


LINQ query with Enumerable / Lambdas

<source lang="vbnet">

Module Program

 Sub Main()
   Dim currentVideoGames() As String = {"A", "B", "this is a test", "C", "D", "E"}
   Dim subset = Enumerable.Where(currentVideoGames, Function(game) game.Length > 6).OrderBy(Function(game) game).Select(Function(game) game)
   For Each game In subset
     Console.WriteLine("Item: {0}", game)
   Next
 End Sub

End Module


 </source>