LINQ to Objects - Does Not Contain?

邮差的信 提交于 2020-01-24 17:22:08

问题


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?


回答1:


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



回答2:


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



回答3:


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



回答4:


Dim notHasGroup = items.Except(haveGroup)



回答5:


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


来源:https://stackoverflow.com/questions/982271/linq-to-objects-does-not-contain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!