LINQ to Objects - Does Not Contain?

2019-07-23 14:54发布

I have a collection of Items that each have a collection of Relationships. I have a list of Groups that Items can have Relationships with.

I can find all the Items that have a particular relationship but I now want to find all the Items that don't have a Relationship with any of my Groups.

I can find the Items that have a relationship with any of the Groups by doing this:

Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
                 Where item.Relationships.Any(Function(r) groupIds.Contains(r.TargetID)) _
                 Select item).ToList

How can I find all the items that do not have a relationship with any of the groups?

5条回答
我只想做你的唯一
2楼-- · 2019-07-23 15:03
Dim listIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
    Where Not listIds.Contains(item.ID) 
    Select item.ID).ToList
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-23 15:06

Have you tried negating the results of the Contains method?

Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
                 Where item.Relationships.Any(Function(r) Not groupIds.Contains(r.TargetID)) _
                 Select item).ToList
查看更多
何必那么认真
4楼-- · 2019-07-23 15:07

I don't remember VB all that well, but a simple "Not" should work.

Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
             Where Not item.Relationships.Any(Function(r) groupIds.Contains(r.TargetID)) _
             Select item).ToList
查看更多
不美不萌又怎样
5楼-- · 2019-07-23 15:12
Dim notHasGroup = items.Except(haveGroup)
查看更多
Bombasti
6楼-- · 2019-07-23 15:20

If you're generating the haveGroup collection anyway then you could just do something like this:

Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList

Dim haveGroup = (From item In items _
    Where item.Relationships.Any(Function(r) groupIds.Contains(r.TargetID)) _
    Select item).ToList

Dim haveNotGroup = items.Except(haveGroup).ToList
查看更多
登录 后发表回答