vb.net中的lambda表达式
时间:2020-03-05 18:54:47 来源:igfitidea点击:
我有某种让我发疯的东西...
Public Function GetAccountGroups() As IList(Of AccountGroup) Dim raw_account_groups As IList(Of AccountGroup) raw_account_groups = _repository.GetAccountGroups().ToList() Dim parents = (From ag In raw_account_groups _ Where ag.parent_id = 0 _ Select ag).ToList() parents(0).sub_account_groups = (From sag In raw_account_groups _ Where sag.parent_id = 0 _ Select sag).ToList() Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _ (From sag In raw_account_groups _ Where sag.parent_id = p.id _ Select sag).ToList() parents.ForEach(Function(p) p.sub_account_groups = sql_func(p)) Return parents End Function
该行" parents.ForEach(Function(p)p.sub_account_groups = sql_func(p))"具有此错误...
没有为类型'System.Collections.Generic.IList(Of st.data.AccountGroup)'和'System.Collections.Generic.List(Of st.data.AccountGroup)'定义运算符'='。
但我真的看不出它与Rob Connery的这段代码有什么不同
public IList<Category> GetCategories() { IList<Category> rawCategories = _repository.GetCategories().ToList(); var parents = (from c in rawCategories where c.ParentID == 0 select c).ToList(); parents.ForEach(p => { p.SubCategories = (from subs in rawCategories where subs.ParentID == p.ID select subs).ToList(); }); return parents; }
哪个可以完美编译...我在做什么错?
解决方案
回答
自从迁移到C3.0以来,我还没有使用过VB.NET,但似乎可能是类型推断问题。由于List实现了IList,因此该错误有些奇怪,因此该分配应该有效。我们可以为lambda说出" p.ID = 123",并且一切似乎正常。
对于有兴趣的人,这里是可以粘贴到新的VB.NET控制台项目中的代码,以演示此问题:
Module Module1 Sub Main() End Sub End Module Class AccountGroup Public parent_id As Integer Public id As Integer Public sub_account_groups As List(Of AccountGroup) End Class Class AccountRepository Private _repository As AccountRepository Public Function GetAccountGroups() As IList(Of AccountGroup) Dim raw_account_groups As IList(Of AccountGroup) raw_account_groups = _repository.GetAccountGroups().ToList() Dim parents = (From ag In raw_account_groups _ Where ag.parent_id = 0 _ Select ag).ToList() parents(0).sub_account_groups = (From sag In raw_account_groups _ Where sag.parent_id = 0 _ Select sag).ToList() Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _ (From sag In raw_account_groups _ Where sag.parent_id = p.id _ Select sag).ToList() parents.ForEach(Function(p) p.sub_account_groups = sql_func(p)) Return parents End Function End Class
回答
我猜" ag.parent_id = 0"应该在" ag.parent_id == 0"的地方?
回答
VB.Net中的Lambda必须返回一个值,因此将等号('=')解释为一个比较(以便lambda返回一个布尔值),而不是赋值。
回答
根据代码,此处接受的答案可能是错误的。 chyne给出了正确的线索:VB中的lambda始终具有返回值(与C#不同),但是在下一版本中引入了语句lambda。
同时,我们根本无法在VB中使用此代码。请改用常规循环:
For Each p In parents p.sub_account_groups = sql_func(p) Next
VB的下一个版本(从昨天开始作为Beta)将允许编写以下代码:
parents.ForEach(Sub (p) p.sub_account_groups = sql_func(p))
回答
使用Sub作为赋值运算符:
parents.ForEach(Sub(p) p.sub_account_groups = sql_func(p))