2

我有一个方法,它需要一个对象列表。
在持久化对象之前,我必须在某些给定条件下删除其中一些

例如(不是理想的!):

一个公司可以有一个 ID 和一个分支列表和一个 IsDeleted 标志。
一个分支可以有一个 Id 和一个经理列表和一个 IsDeleted 标志
一个经理可以有一个 Id 和一个 IsDeleted 标志
Company -->Branches-->Managers

什么是最简单或最好的过滤方式来省略 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
4

3 回答 3

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
于 2012-09-22T22:12:45.760 回答
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
于 2012-09-22T22:13:47.473 回答
0

在迭代的每个级别中,循环遍历该级别上的所有现有元素。使用 if 语句检查 ID=0 和 IsDeleted 是否为真,在这种情况下删除条目。

于 2012-09-22T22:15:06.660 回答