gpt4 book ai didi

c# - VB.NET 中对 Linq/lambda 的混淆

转载 作者:行者123 更新时间:2023-11-30 20:09:13 26 4
gpt4 key购买 nike

我有一个 DTO 的集合,Department,并且只想为所有 Department 对象提取其中一个列。我知道在 C# 中你可以这样做:

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

为什么会这样?我错过了什么吗?

最佳答案

您也可以在 Visual Basic .NET 中使用 lambda。语法是这样的:

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

对于不返回值的 lambda(如 Action<int> 类型的那些),使用 Sub相反:

Sub(x) Console.WriteLine(x)

关于c# - VB.NET 中对 Linq/lambda 的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6342989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com