我有一个获取对象列表的方法 在持久化对象之前,我必须在某些特定情况下删除它们中的一些
例如(不是理想的!):
公司可以拥有Id和分支列表以及IsDeleted标志 分支可以有一个Id和一个Managers列表以及一个IsDeleted标志
经理可以拥有Id和IsDeleted标志 公司 - >分行 - >经理
什么是简单或最好的过滤方式,以省略Id = 0和IsDeleted = True的组合,以便我可以迭代并执行具体操作 - 请参阅下面的函数
Id = 0 and IsDeleted
,那么我想完全省略Id=0 and Isdeleted
,那么公司应该没有分支Id=0 and Isdeleted
,那么公司和分公司应该在那里Private Function(comp as List(Of Company)) as Boolean
'filter comp here and pass it to for loop??
Dim filteredList as ...
For each c as Company in filteredList
'do company specifis here
For each b as Branch in c.Branches
'do branch specific here
For Each m as Manager in b.Managers
'do manager specific here
Next
Next
Save(c) ' saves child objects as well
Next
End Function
答案 0 :(得分:2)
你可以使用Linq:
Dim filtered = From c In comp Where Not c.IsDeleted OrElse c.Id <> 0
From b In c.Branches Where Not b.IsDeleted OrElse b.Id <> 0
From m In b.Managers Where Not m.IsDeleted OrElse m.Id <> 0
Select New With {.Company = c, .Branch = b, .Manager = m}
For Each x In filtered
Dim c As Company = x.Company
Dim b As Branch = x.Branch
Dim m As Manager = x.Manager
Next
或者,如果您想分别枚举每种类型:
Dim filteredComp = From c In comp Where Not c.IsDeleted OrElse c.Id <> 0
Dim filteredBranch = From c In filteredComp
From b In c.Branches Where Not b.IsDeleted OrElse b.Id <> 0
Select b
Dim filteredManager = From b In filteredBranch
From m In b.Managers Where Not m.IsDeleted OrElse m.Id <> 0
Select m
For Each c In filteredComp
Next
For Each b In filteredBranch
Next
For Each m In filteredManager
Next
答案 1 :(得分:1)
这会解决您的问题吗?
Dim filtererdComp = comp _
.Where(Function(c) c.Id<>0 Or Not c.IsDeleted)
.ToList()
For each c as Company in filtererdComp
c.Branches = c.Branches _
.Where(Function(b) b.Id<>0 Or Not b.IsDeleted) _
.ToList()
For each b As Branch in c.Branches
b.Managers = b.Managers _
.Where(Function(m) m.Id<>0 Or Not m.IsDeleted) _
.ToList()
Next
Next
答案 2 :(得分:0)
在迭代的每个级别中,循环遍历该级别上的所有现有元素。使用if语句检查ID = 0和IsDeleted是否为true,在这种情况下删除该条目。