2011-06-14 48 views
2

我有一個DTO,Department的集合,並且想要爲所有Department對象只提取其中一列。我知道,在C#中,你可以這樣做:對VB.NET中Linq/lambdas的混淆

List<Department> departments = corporation.GetDepartments(); 
List<int> departmentIDs = departments.ConvertAll(dep => dep.ID); 

走出我的理解,這是使用LINQ的,與參數ConvertAll()是一個lambda表達式。

當試圖實現在VB一樣,似乎一個必須定義一個轉換法(?):

Dim departmentIDs As List(Of Integer) = coll.ConvertAll(New Converter(Of Department, Integer)(AddressOf ConvertDepartmentToInt)) 

Public Shared Function ConvertDepartmentToInt(ByVal dep As Department) As Integer 
    Return dep.ID 
End Function 

爲什麼會這樣呢?我錯過了什麼嗎?

回答

7

也可以在Visual Basic .NET中使用lambdas。語法是這樣的:

departments.ConvertAll(Function(dep) dep.ID) 

對於不返回值(像那些Action<int>型)lambda表達式,使用Sub代替:

Sub(x) Console.WriteLine(x) 
+0

謝謝!這種語法似乎比C#語法文檔少。也許是因爲人氣趨向C#.. – 2011-06-14 12:03:54