views:

1498

answers:

4

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?

+6  A: 

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
Andrew Hare
This answer is incorrect. This matches all items that have one or more Relationships that don't match, as opposed to all items that have no matching Relationships.
Thorarin
This was what I had originally tried, but as Thorarin correctly points out, it returned all of the items in the original group rather than excluding those with any matches.
Nick
+3  A: 

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
StriplingWarrior
Thanks, that's spot on. :)
Nick
+2  A: 

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
LukeH
A: 
Dim notHasGroup = items.Except(haveGroup)
Joe Chung